首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Python中创建服务器(localhost),然后将数据发送到url/ server,然后检索数据?

如何在Python中创建服务器(localhost),然后将数据发送到url/ server,然后检索数据?
EN

Stack Overflow用户
提问于 2020-03-25 12:00:39
回答 1查看 59关注 0票数 2

有人知道我的代码出了什么问题吗?

代码语言:javascript
复制
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,服务器部分看起来工作正常,但是当我尝试发布和获取数据时,我得到一个错误

代码语言:javascript
复制
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 -

代码语言:javascript
复制
127.0.0.1 - - [24/Mar/2020 20:52:00] code 404, message File not found
127.0.0.1 - - [24/Mar/2020 20:52:00] "GET /get-data HTTP/1.1" 404 -

编辑:我想通了,在评论中查看我的解决方案

EN

回答 1

Stack Overflow用户

发布于 2020-03-26 04:20:47

我想通了:

代码语言:javascript
复制
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())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60842821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档