Python:运行SimpleHTTPServer并在脚本中对其发出请求 [英] Python: run SimpleHTTPServer and make request to it in a script

查看:313
本文介绍了Python:运行SimpleHTTPServer并在脚本中对其发出请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写Python脚本,该脚本将:

I would like to write Python script that would:

  1. 在某些端口上启动SimpleHTTPServer
  2. 向服务器发送请求,并通过POST发送一些数据
  3. 以交互方式通过shell运行脚本并与其交互

现在,代码如下所示:

import SimpleHTTPServer
import SocketServer
import urllib
import urllib2

# Variables
URL = 'localhost:8000'
PORT = 8000

# Setup simple sever
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()

# Getting HTML from the target page
values = {
    'name': 'Thomas Anderson',
    'location': 'unknown'
}
data = urlilib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
html = response.read()

问题在于,一旦我运行脚本

The problem is that once I run my script

python -i foo.py

它打印serving at port 8000,然后冻结.我敢打赌,这对于Python专家来说是微不足道的,但是可以得到帮助.

It prints serving at port 8000 and then freezes. I bet this is something trivial for Python gurus here, but help would be appreciated.

推荐答案

将服务器作为不同进程运行,这将允许您运行脚本的其余部分.

Run the server as a different process, that will allow you to run the rest of your script.

我还宁愿使用请求而不是urllib.

I would also rather use requests than urllib.

import SocketServer
import SimpleHTTPServer

import requests
import multiprocessing

# Variables
PORT = 8000
URL = 'localhost:{port}'.format(port=PORT)

# Setup simple sever
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "Serving at port", PORT

# start the server as a separate process
server_process = multiprocessing.Process(target=httpd.serve_forever)
server_process.daemon = True
server_process.start()

# Getting HTML from the target page
values = {
    'name': 'Thomas Anderson',
    'location': 'unknown'
}

r = requests.post(URL, data=values)
r.text

# stop the server
server_process.terminate()

这篇关于Python:运行SimpleHTTPServer并在脚本中对其发出请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆