如何创建一个服务器(localhost),然后继续将数据发布到该url/服务器,然后检索它,所有这些都在Python中完成?
有人知道我的代码有什么问题吗如何创建一个服务器(localhost),然后继续将数据发布到该url/服务器,然后检索它,所有这些都在Python中完成?,python,http,server,python-requests,Python,Http,Server,Python Requests,有人知道我的代码有什么问题吗 import requests import http.server import socketserver import threading PORT = 8080 Handler = http.server.SimpleHTTPRequestHandler # creates a server at url: http://locahost:8080 def create_server(): with socketserver.TCPServer((
import requests
import http.server
import socketserver
import threading
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
# creates a server at url: http://locahost:8080
def create_server():
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT, flush=True)
httpd.serve_forever()
try:
thread = threading.Thread(target=create_server, args=())
thread.start()
r = requests.post('http://localhost:8080/get-data', data={'key': 'value'})
b = requests.get('http://localhost:8080/get-data')
print(b.json())
except:
print('starting the server was unsuccessful')
我为服务器准备了一个index.html,服务器部分似乎工作正常,但当我试图发布和获取数据时,我得到了一个错误消息
127.0.0.1 - - [24/Mar/2020 20:51:58] code 501, message Unsupported method ('POST')
127.0.0.1 - - [24/Mar/2020 20:51:58] "POST /get-data HTTP/1.1" 501 -
及
编辑:我算出了,在评论中查看我的解决方案我算出了:
import requests
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
# 8000 doesn't mean anything, feel free to change to any other 4 digit number
PORT = 8000
# if you haven't seen this syntax before, it's Python's inheritance,
# and in this case it means MyHandler extends BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200) # 200 stands for request succeeded
self.send_header("Content-type", "text/html") # informs requests of the Media type
self.end_headers()
# entering the localhost url into your browser, you will get an additional /favicon.ico path,
# so take this into account with testing.
# this method is where
def do_GET(self):
self._set_headers()
print(self.path) # if url is localhost:8000/test, self.path would equal '/test'
if self.path == '/hello-there':
json_string = json.dumps({'hello': 'back', 'received': 'ok'}) # converts dictionary to a JSON string
self.wfile.write(json_string.encode(encoding='utf_8')) # like before, encode to avoid TypeError
# the above line is what actually sends data back to client on a request for data
def run(server_class=HTTPServer, handler_class=MyHandler, addr="localhost", port=PORT):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}") # f before string allows special formatting
httpd.serve_forever()
# the next line basically checks if your configurations set this file as the "main" file,
# and if so, run the following code.
# if this code is imported into another project, that means the following code won't run,
# because this file is not the main file.
if __name__ == "__main__":
thread = threading.Thread(target=run)
# if threading isn't used, all code after serve_forever() (line 43) would not run
thread.start()
url = f'http://localhost:{PORT}/hello-there'
request = requests.get(url)
print(request.json())
import requests
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
# 8000 doesn't mean anything, feel free to change to any other 4 digit number
PORT = 8000
# if you haven't seen this syntax before, it's Python's inheritance,
# and in this case it means MyHandler extends BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200) # 200 stands for request succeeded
self.send_header("Content-type", "text/html") # informs requests of the Media type
self.end_headers()
# entering the localhost url into your browser, you will get an additional /favicon.ico path,
# so take this into account with testing.
# this method is where
def do_GET(self):
self._set_headers()
print(self.path) # if url is localhost:8000/test, self.path would equal '/test'
if self.path == '/hello-there':
json_string = json.dumps({'hello': 'back', 'received': 'ok'}) # converts dictionary to a JSON string
self.wfile.write(json_string.encode(encoding='utf_8')) # like before, encode to avoid TypeError
# the above line is what actually sends data back to client on a request for data
def run(server_class=HTTPServer, handler_class=MyHandler, addr="localhost", port=PORT):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}") # f before string allows special formatting
httpd.serve_forever()
# the next line basically checks if your configurations set this file as the "main" file,
# and if so, run the following code.
# if this code is imported into another project, that means the following code won't run,
# because this file is not the main file.
if __name__ == "__main__":
thread = threading.Thread(target=run)
# if threading isn't used, all code after serve_forever() (line 43) would not run
thread.start()
url = f'http://localhost:{PORT}/hello-there'
request = requests.get(url)
print(request.json())