开发者社区> 问答> 正文

没有Djangp REST框架的Python简单API应用程序

我需要使用Python创建一个简单的API。

有很多使用Django REST框架制作REST API的教程,但是我不需要REST服务,我只需要能够处理POST请求。

我怎样才能做到这一点?我是Python的新手。

谢谢!

展开
收起
祖安文状元 2020-02-22 18:09:28 574 0
1 条回答
写回答
取消 提交回答
  • 您可以将HTTPServer模块与SimpleHTTPRequestHandler一起使用,以创建一个简单的Web服务器来服务GET和POST请求

    from http.server import BaseHTTPRequestHandler,HTTPServer, SimpleHTTPRequestHandler
    
    class GetHandler(SimpleHTTPRequestHandler):
    
            def do_GET(self):
                SimpleHTTPRequestHandler.do_GET(self)
    
            def do_POST(self):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.data_string = self.rfile.read(int(self.headers['Content-Length']))
    
                data = b'<html><body><h1>POST!</h1></body></html>'
                self.wfile.write(bytes(data))
                return
    
    Handler=GetHandler
    
    httpd=HTTPServer(("localhost", 8080), Handler)
    httpd.serve_forever()
    
    2020-02-22 18:09:38
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Boot2.0实战Redis分布式缓存 立即下载
CUDA MATH API 立即下载
API PLAYBOOK 立即下载