美文网首页
Python全栈快餐教程(1) - 用Flask处理HTTP请求

Python全栈快餐教程(1) - 用Flask处理HTTP请求

作者: Jtag特工 | 来源:发表于2019-10-31 17:52 被阅读0次

    Python全栈快餐教程(1) - 用Flask处理HTTP请求

    初识Flask

    Flask是最流行的Python web框架之一。

    我们来写个最小的web应用,只有一个路由先跑进来玩玩吧。

    from flask import Flask
    
    # 定义flask app对象
    app = Flask(__name__)
    
    # 处理路由
    @app.route('/')
    def index():
        return "<h1>It works!</h1>"
    
    # 运行起来,这里可以指定端口和调试属性等
    app.run(port=30000,debug=True)
    

    处理url路径中的数据

    比如要处理http://localhost:30000/code/test,从中获取test这个字符串,可以这样写:

    @app.route('/code/<code>')
    def complete(code):
        print('Received code:%s' % code)
        return 'Hello, %s' % code
    

    处理post消息

    axios出场

    要处理post消息的话,首先需要发送post消息,我们选择在前端来做这事儿吧。前端么,自然是js语言了,我们配上axios库。

    我们在node.js里写一下:

    const axios = require('axios');
    
    const instance = axios.create({
      baseURL: 'http://127.0.0.1:30000',
      timeout: 1000});
    
    instance.post('/complete', {code:'#include <iostream>试试中文行不行'})
    .then(function (response) {
      console.log('complete: '+response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
    

    处理post数据

    其实非常简单,只要把request的data读出来就好了。因为我们从js送过来的是一个字节编码的json串,所以我们先解码一下,然后转成json格式,最后读取一下相应字段就好了:

    @app.route('/complete', methods=['POST'])
    def code_complete():
        code = request.data.decode()
        code2 = json.loads(code)
        return 'Hello'+code2.get('code')
    

    一些小trick

    • Windows机器的名字不要用中文,否则flask无法启动
    • 不要用6666端口,否则Chrome不认
    • POST的消息要处理,否则会报keyError返回一个错误页面

    相关文章

      网友评论

          本文标题:Python全栈快餐教程(1) - 用Flask处理HTTP请求

          本文链接:https://www.haomeiwen.com/subject/axitbctx.html