简单的接收和返回Python服务器?

时间:2019-01-08 17:39:38

标签: python-3.x http server

我需要在本地启动Python服务器以进行测试。它所需要做的就是用请求中收到的JSON进行回复。

我已经使用Node.js实现了所需的功能。我想用Python重写它,因为它已用于测试Python服务。我还没有找到任何清晰的示例说明如何执行此操作。据我所知,它需要我目前尚不具备的网络编程知识(有关网络级别正在发生的事情的解释和/或资源材料,将不胜感激!)

下面的Node.js代码:

#!/usr/bin/env node
const http = require("http");

const PORT = process.argv[2]

const server = http.createServer((req, res) => {
    let data = "";
    req.on("error", err => {
        throw err;
    });
    req.on("data", chunk => {
        data += chunk;
    });
    req.on("end", () => {
        res.setHeader("Content-Type", "application/json")
        res.write(data, () => res.end());
    });
});

server.listen(PORT, () => {
    console.log(`Dummy server listing on port: ${PORT}`)
});

1 个答案:

答案 0 :(得分:0)

Python有很多框架,一个简单的Flask框架!

https://medium.com/@aliciagilbert.itsimplified/a-slick-crud-application-built-using-python-with-flask-and-sqlite3-to-teach-simple-mysql-queries-bd75e1109582

[已更新]

#!/usr/bin/python

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route("/")
def index():
    parameter= request.args.get('parameter', default = 1, type = int)
    return "Hello Flask!"

if __name__ == '__main__':
    app.run(debug=True)

保存在app.py中并运行“ python app.py”,默认情况下将在端口5000上进行监听-http://localhost:5000/