标签: basehttpserver

使用BaseHTTPRequestHandler重定向功能

这是我的代码:

from http.server import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'some text')

def redirect(location):
    # redirect

server = HTTPServer(('localhost', 1111), Handler)
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

如何编写函数以从路径重定向到另一个?

basehttpserver python-3.x basehttprequesthandler

4
推荐指数
1
解决办法
3084
查看次数

在后台运行Python HTTPServer并继续执行脚本

我试图找出如何在运行".serve.forever()方法后在后台运行我重载的自定义BaseHTTPServer实例.

通常,当您运行该方法时,执行将挂起,直到您执行键盘中断,但我希望它在后台继续执行脚本时提供请求.请帮忙!

python basehttpserver python-multithreading python-daemon

4
推荐指数
1
解决办法
5492
查看次数

从BaseHTTPServer解析Python HTML POST数据

我将一些HTML表单中的文件发送到基于BaseHTTPServer的服务器.

在我的do_POST中,我从rfile.read(length)获取一个字符串,它看起来像某种多部分MIME字符串.谷歌在如何将其解码为可用的东西方面没有帮助.

输出如下所示:

-----------------------------122422713313797828591978698502

Content-Disposition: form-data; name="MAX_FILE_SIZE"



1000000

-----------------------------122422713313797828591978698502

Content-Disposition: form-data; name="and_title_input"
Run Code Online (Sandbox Code Playgroud)

等等.

我试过email.parser

from email.parser import Parser 
p=Parser()
msg=p.parsestr(s)
Run Code Online (Sandbox Code Playgroud)

但是msg似乎并没有让我更接近我的目标 - 它不是多部分并且不包含有效载荷.

我沦为自己解析数据 - 这肯定不是Pythonic的做事方式!

我错过了一些明显的事吗?谷歌让我失望了吗?Stack Stack Overflow可以节省一天吗?

python post http basehttpserver

3
推荐指数
1
解决办法
4860
查看次数

如何在BaseHTTPServer.BaseHTTPRequestHandler Python中实现Timeout

在我的python脚本中,我正在尝试运行Web服务器:

server = BaseHTTPServer.HTTPServer(('127.0.0.1',8080), RequestHandler)
Run Code Online (Sandbox Code Playgroud)

我有一个请求处理程序类:

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        # Doing Some Stuff.
Run Code Online (Sandbox Code Playgroud)

现在我总是等待一些数据来捕获do_GET.我想实现一个超时操作,我希望这个Web服务器在60秒之后关闭.我无法实现这一点.请建议我如何在这种情况下为Web服务器实现自动关闭操作.

谢谢Tara Singh

python basehttpserver

3
推荐指数
2
解决办法
7462
查看次数

如何从Python中的请求处理程序中关闭HTTPServer?

收到StopIteration异常后,如何关闭此服务器?sys.exit()不起作用.

#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 2000

from itertools import islice
filename = 'data/all.txt'
file = open(filename, 'r')
lines_gen = islice(file, None)

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global lines_gen

        self.send_response(200)
        self.send_header('Content-type','text/plain')
        self.end_headers()

        try:
            for i in range(10):
                next_line = lines_gen.next()
                self.wfile.write(next_line)
        except StopIteration:
            # return response and shutdown the server
            # ?????

        return

try:
    server = HTTPServer(('', PORT_NUMBER), MyHandler)
    print('Started httpserver on port ' , PORT_NUMBER)
    server.serve_forever()

except KeyboardInterrupt:
    print('^C received, shutting down the web server')
    server.socket.close()
Run Code Online (Sandbox Code Playgroud)

python basehttpserver

3
推荐指数
1
解决办法
5363
查看次数

如何使用Python发送和接收HTTP POST请求?

我有以下两个Python脚本,用于尝试弄清楚如何在Python中发送和接收POST请求:

客户端:

import httplib

conn = httplib.HTTPConnection("localhost:8000")
conn.request("POST", "/testurl")
conn.send("clientdata")
response = conn.getresponse()
conn.close()

print(response.read())
Run Code Online (Sandbox Code Playgroud)

服务器:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

ADDR = "localhost"
PORT = 8000

class RequestHandler(BaseHTTPRequestHandler):        
    def do_POST(self):
        print(self.path)
        print(self.rfile.read())
        self.send_response(200, "OK")
        self.end_headers()
        self.wfile.write("serverdata")

httpd = HTTPServer((ADDR, PORT), RequestHandler)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

问题是服务器挂在self.rfile.read()上,直到在客户端上调用conn.close()为止,但是如果在客户端上调用conn.close(),则客户端无法从服务器接收响应。这就造成了一种情况,要么可以从服务器获得响应,要么可以读取POST数据,但不能两者兼有。我认为这里缺少某些东西可以解决此问题。

附加信息:

conn.getresponse()使客户端挂起,直到从服务器接收到响应为止。在服务器上的功能完成执行之前,似乎没有收到响应。

python post http basehttpserver httplib

3
推荐指数
1
解决办法
2万
查看次数

为什么do_GET比do_POST快得多

Python的BaseHTTPRequestHandler对于通过邮寄发送的表单存在问题!

我见过其他人问同样的问题(为什么GET方法比POST更快?),但我的情况时差太大(1秒)

Python服务器:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import datetime


def get_ms_since_start(start=False):
    global start_ms
    cur_time = datetime.datetime.now()
    # I made sure to stay within hour boundaries while making requests
    ms = cur_time.minute*60000 + cur_time.second*1000 + int(cur_time.microsecond/1000)
    if start:
        start_ms = ms
        return 0
    else:
        return ms - start_ms

class MyServer(BaseHTTPRequestHandler, object):
    def do_GET(self):
        print "Start get method at %d ms" % get_ms_since_start(True)
        field_data = self.path
        self.send_response(200)
        self.end_headers()
        self.wfile.write(str(field_data))
        print "Sent response at %d ms" % get_ms_since_start()
        return

    def …
Run Code Online (Sandbox Code Playgroud)

post http basehttpserver httpserver basehttprequesthandler

3
推荐指数
1
解决办法
669
查看次数

如何从BaseHTTPRequestHandler访问HTTPServer的成员?

我正在整理一个涉及GUI,HTTP和TCP服务器的小应用程序.GUI控制从HTTP和TCP服务器返回到客户端的响应.我使用HTTPServer和SocketServer.TCPServer类作为服务器,具有BaseHTTPRequestHandler和StreamRequestHandler的子类.但是让我们首先关注事物的HTTP方面.

当HTTPServer收到请求时,它应该检查GUI的状态,并做出适当的响应.我已经将一个成员变量添加到指向GUI的HTTPServer,但是无法找到从BaseHTTPRequestHandler子类访问该字段的好方法.如何才能做到这一点?

下面是我目前的代码,虽然Python抛出异常,MyHTTPHandler instance has no attribute 'server':

class MyHTTPHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
        self._server = server

    def do_GET(self):
        self._server.get_interface().do_something()
        [...]
Run Code Online (Sandbox Code Playgroud)

python basehttpserver httpserver

2
推荐指数
1
解决办法
1826
查看次数

响应中的 Http 版本 BaseHttp 模块 python

我正在使用带有 Python 的 BaseHttp 运行服务器。

我收到来自基于 HTTP/1.1 的客户端的请求

但是,当我用我的回复回复客户时,客户拒绝接受我的回复。在进一步分析中,我看到我发送的 HTTP 版本是 HTTP/1.0。但是,我不知道它是如何设置的。

客户端的错误是。

Original message: not well-formed (invalid token): line 2, column 4 
Response 
HTTP/1.0 200 OK
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 30 Jul 2014 15:11:42 GMT
Content-type: application/soap+xml; charset=utf-8
Content-length: 823
Run Code Online (Sandbox Code Playgroud)

我按以下方式设置标题:

self.send_response(200)
self.send_header("Content-type", "application/soap+xml; charset=utf-8")
self.send_header("Content-length", content_length)
self.end_headers()
Run Code Online (Sandbox Code Playgroud)

python basehttpserver

2
推荐指数
1
解决办法
1656
查看次数

Python - BaseHTTPServer 保持活动状态不起作用

我有一个基于 BaseHTTPServer 的简单服务器的以下代码。

class myHandler(BaseHTTPRequestHandler):
    #Handler for the GET requests
    def do_GET(self):
        # Parse the query_str
        query_str = self.path.strip().lower()
        if query_str.startswith("/download?"):
            query_str = query_str[10:]
            opts = urlparse.parse_qs(query_str)

            # Send the html message and download file
            self.protocol_version = 'HTTP/1.1'
            self.send_response(200)
            self.send_header("Content-type", 'text/html')
            self.send_header("Content-length", 1)
            self.end_headers()
            self.wfile.write("0")

            # Some code to do some processing
            # ...
            # -----------

            self.wfile.write("1")
Run Code Online (Sandbox Code Playgroud)

我原本期望 HTML 页面显示“1”,但它显示“0”。如何通过 keepalived 更新响应?

python basehttpserver

2
推荐指数
1
解决办法
7531
查看次数

删除 python HTTP 服务器中的缓存

我在网上找到了这个服务器并对其进行了一些编辑。这是代码:

from http.server import BaseHTTPRequestHandler, HTTPServer
from xml.dom import minidom
import os


class MyHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        self.data_string = self.rfile.read(int(self.headers['Content-Length']))
        self.send_response(200)
        self.end_headers()
        valore = str(self.data_string)[2:-1]
        response = ["",""]
        response[0],response[1] = processData(valore)
        if response[0] == 1:
            sep = ""
            message = ""
            for res in response[1]:
                message += res
            response = sep.join(message)
            self.wfile.write(bytes(message, "utf-8"))

    def do_GET(self):
        # Send response status code
        self.send_response(200)
        # Send headers
        if self.path.endswith("html"):
            self.send_header('Content-type', 'text/html')
            self.end_headers()
        elif self.path.endswith("css"):
            self.send_header('Content-type', 'text/css')
            self.end_headers()
        elif self.path.endswith("js"):
            self.send_header('Content-type', 'application/javascript')
            self.end_headers()
        elif self.path.endswith(".ico"): …
Run Code Online (Sandbox Code Playgroud)

python caching basehttpserver server

2
推荐指数
1
解决办法
1万
查看次数