简体   繁体   English

python sys.stdout.write()重定向

[英]python sys.stdout.write() redirect

i am redirecting a proxy server to my script which checks the URL, User-Agents etc and based on the checks it returns the user to specified URL. 我将代理服务器重定向到我的脚本,该脚本检查URL,User-Agent等,并根据检查将用户返回到指定的URL。

now if i send a GET request back to the client it works, but it display only text version of the site with no css/images, this is part of the code which sends the request back to the client.. 现在,如果我将GET请求发送回客户端,则可以正常工作,但它仅显示站点的文本版本,而没有CSS /图像,这是将请求发送回客户端的代码的一部分。

if l.startswith('User-Agent:') and ('Safari' in l):

    new = "http://www.yahoo.com"
    new_get = "GET" + " " + str(new) + " " + "HTTP/1.1" + "Status: 302" + "\r\n\r\n"
    sys.stdout.write(new_get)
    sys.stdout.flush()

i have tried to set 我试图设定

new = "302:http://www.yahoo.com"

but does not work either... 但也不起作用...

any ideas?? 有任何想法吗??

UPDATED: 更新:

if l.startswith('User-Agent:') and ('Safari' in l):

    new = "http://www.yahoo.com"
    new_get = "GET" + " " + str(new) + " " + "HTTP/1.1" + "Status: 302" + "\r\n\r\n"
    uopen = urllib2.urlopen("http://www.yahoo.com")
    sys.stdout.write(uopen.read())
    sys.stdout.flush()

tried with urllib2 and its takes a lot of time for the browser to render the page..but same results..no images/css.. 尝试使用urllib2,并且浏览器呈现页面需要花费很多时间。但是结果相同。没有图像/ css。

If you want to redirect the client: 如果要重定向客户端:

new_url = 'http://www.yahoo.com/'

print 'Status:', '302 Found'
print 'Location:', new_url
print

If instead you want to serve something directly to the client: 相反,如果您想直接为客户提供服务:

from shutil import copyfileobj
from sys import stdout
from urllib2 import urlopen

http_message = urlopen("http://www.yahoo.com")
copyfileobj(http_message, stdout)

Why are you doing all this by hand? 你为什么要手工做这一切? The Python standard library contains modules such as urllib2 and httplib , and even SimpleHTTPServer to help you with tasks like these. Python标准库包含诸如urllib2httplib模块,甚至包括SimpleHTTPServer来帮助您完成这些任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM