Javascript

几行代码支持POST和json; python HTTP server; Flask

本文主要是介绍几行代码支持POST和json; python HTTP server; Flask,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

用python做个HTTP server,界面用HTML+CSS+JavaScript来写不错——不用学那么多种东东了。JS的UI框架多如牛毛,功能强大,普通的界面都能应付。python自带HTTP server:

from http.server import *
class HTTPReqHandler(SimpleHTTPRequestHandler):
    def __init__(m, r, c, s): super().__init__(r, c, s, directory='www')
    def do_GET(m):
        path = m.requestline.split(' ')[1]
        if not path.startswith('/ucci'): return super().do_GET()
        param = re.split('[\?\<]', urllib.parse.unquote(path))
        m.send_response(200)
        m.send_header('Content-type', 'text/html')
        m.end_headers()
        ee.send(param[2]); print(param[2])
        if param[1] != 'none': m.wfile.write(ee.recv(param[1]))
    def do_HEAD(m): super().do_HEAD()
    def do_POST(m): super().do_POST()

一直满足于GET,昨天才发现SimpleHTTPRequestHandler没实现do_POST(). 所以试了flask:

try: from flask import Flask, jsonify, send_file, request
except: print("This program needs flask; please run 'pip install flask' first.")

app = Flask(__name__, root_path='www')

@app.route('/')
def root_file(): return send_file('index.html')
# Flask返回个对象app,它有成员函数route,which is a decorator.
# 描述了规则: GET / ? 发index.html

@app.route('/parse-vcd', methods = ['POST']) # 处理POST /parse-vcd
def parse_vcd():
    content = None; fname = None
    try: content = request.json['content']
    except KeyError: logging.error('No content, try to open the file locally.')
    try: fname = request.json['fname']
    except KeyError: logging.error('No filename')
    logging.info(f'File to parse: {fname}')
    try:
        data = parseFile(os.path.join(here, fname), content)
        return jsonify(data)
    except Exception as e: logging.error(f'Error: {e}')
# 支持POST了。

os.environ["FLASK_ENV"] = 'development'
app.run(port=8000, debug=False)

The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application.Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. Web服务器网关接口(Python Web Server Gateway Interface,缩写为WSGI)是为Python语言定义的Web服务器和Web应用程序或框架之间的一种简单而通用的接口。自从WSGI被开发出来以后,许多其它语言中也出现了类似接口。

CGI (Common Gateway Interface)最早,是HTTP服务器每次去执行.exe,效率低。后来有了FastCGI, 它也是个server,和HTTP server之间通过socket等通讯,用FastCGI而不是H他TP协议。后来有了PHP和ASP,HTTP服务器带解释功能。我认为这个很好,大段的printf("<a href=\"....\">xxx</a>")实在是太繁琐了。然后serverlet啦,soap啦,好比http;//host/prog, 在server端真有个prog类/module…… 重大发明?Sun早就有RPC(Remote Procedure Call)了。

这篇关于几行代码支持POST和json; python HTTP server; Flask的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!