Web proxy in python/django?

2019-05-25 01:14发布

I need to have a proxy that acts as an intermediary to fetch images. An example would be, my server requests domain1.com/?url=domain2.com/image.png and domain1.com server will respond with the data at domain2.com/image.png via domain1.com server.

Essentially I want to pass to the proxy the URL I want fetched, and have the proxy server respond with that resource.

Any suggestions on where to start on this?

I need something very easy to use or implement as I'm very much a beginner at all of this.

Most solutions I have found in python and/or django have the proxy acts as a "translater" i.e. domain1.com/image.png translates to domain2.com/image.png, which is obviously not the same.

I currently have the following code, but fetching images results in garbled data:

import httplib2
from django.conf.urls.defaults import *
from django.http import HttpResponse

def proxy(request, url):
    conn = httplib2.Http()
    if request.method == "GET":
        url = request.GET['url']
        resp, content = conn.request(url, request.method)
        return HttpResponse(content)

3条回答
Emotional °昔
2楼-- · 2019-05-25 01:15

Use mechanize, it allow you to choose a proxy and act like a browser, making it easy to change the user agent, to go back and forth in the history and to handle authentification or cookies.

查看更多
老娘就宠你
3楼-- · 2019-05-25 01:30

If the file you're fetching and returning is an image, you'll need to change the mimetype of your HttpResponse Object.

查看更多
叼着烟拽天下
4楼-- · 2019-05-25 01:40

Old question but for future googlers, I think this is what you want:

# proxies the google logo
def test(request):
    url = "http://www.google.com/logos/classicplus.png"
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    return HttpResponse(response.read(), mimetype="image/png")
查看更多
登录 后发表回答