• 常用业务接口界面化 in python flask


    背景:

    对于业务测试来说,有一些基础业务接口是需要经常调用的,如根据userId查询某人的信息,修改某人的xx属性,一般的接口都有验签(或者说token)机制,使用postman等工具的话,也是需要去自定义解决的,因此决定写个页面更简易化

    思路:

    为了快速实现功能,决定采用python的flask框架,使用了flask-wtf(form表单),flask-bootstrap(美化界面),ajax

    app.py,启动程序

    from flask import Flask, render_template,request
    from flask_bootstrap import Bootstrap
    from works import *
    from myForm import ReqForm
    
    
    app = Flask(__name__)
    app.config.from_object('config')
    Bootstrap(app)
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        form = ReqForm()
        
        if  request.method == "POST":
            result = getReq(request.form.get( "url", "null"))
            return result
        
        return render_template("index.html", form=form)
    
    if __name__ == "__main__":
        app.run(host='0.0.0.0',debug=True)

    form.py 表单对象

    from flask_wtf import FlaskForm
    from wtforms import StringField, SubmitField, TextAreaField, SelectField
    from wtforms.validators import DataRequired
    
    
    class ReqForm(FlaskForm):
        method = SelectField(u'Method', choices=[('get', 'GET'), ('post', 'POST'), ('delete', 'DELETE')])
        url = StringField('Please enter the URL: ', validators=[DataRequired()])
        reqBody = TextAreaField("Request Body: ",render_kw={'class':'text-body','rows':15})
        submit = SubmitField("Send")

    index.html,页面展示层,用来渲染页面的

    {% block head %}
    <title>test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    {% endblock %}
    
    {% import "bootstrap/wtf.html" as wtf %} 
    
    {% block page_content %}
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-6 column">
                <form class="form" method="post">
                    {{form.hidden_tag()}}
                    {{wtf.form_field(form.method)}} 
                    {{wtf.form_field(form.url)}}
    
                    {{wtf.form_field(form.reqBody)}}
                    {{wtf.form_field(form.submit)}}
    
            </form>
            </div>
            <div class="col-md-6 column">
                <h3>Result:</h3>
                <textarea id="textarea" class="form-control text-body" rows="21">{{result}}</textarea>
            </div>
        </div>
    </div>
    {% endblock %}
    
    {% block scripts %}
    <script src="{{ url_for('static', filename='js/jquery-3.2.1.min.js') }}"></script>
    <script type=text/javascript>  
    var $SCRIPT_ROOT = {{request.script_root|tojson|safe}};  
    </script> 
    <script type="text/javascript">
    
    $(document).ready(function(){
        $("#submit").click(function(){
            $.post("/",
            {
                url: $( "#url" ).val(),
            },
            function(data,status){
                $( "#textarea" ).text(data);  
            }           
            );
            return false
          });
        });
    </script>
    {% endblock %}

    work.py,实际接口的处理

    import requests
    import json
    
    def getReq(url):
        r = requests.get(url)
        return json.dumps(json.loads(r.text), indent=4, sort_keys=False, ensure_ascii=False)

    大概流程:

    app.py启动后,通过实例化一个form表单,然后通过render_template指向到index.html,页面展示OK,页面上的submit绑定了js事件,将页面上的元素组装成post请求指向后台的地址,后台通过request获取到前端页面的值后,通过work.py的业务处理后return值返回前端,再展示会前端,这块使用了ajax

    最终页面如下:

    可以根据业务处理成如下:

    作者:jwentest
    虽千万人,吾往矣!文章先发到语雀:https://www.yuque.com/qianwang/testway
  • 相关阅读:
    Service Discovery
    Spring security框架原理
    Redis作者谈Redis应用场景
    redis持久化RDB和AOF-转载
    MongoDB树形结构表示法
    Tomcat Connector
    ActiveMQ 负载均衡与高可用(转载)
    JS选取DOM元素的方法
    IObit Driver Booster 无法更新驱动的解决办法
    python 学习备忘
  • 原文地址:https://www.cnblogs.com/jwentest/p/7067291.html
Copyright © 2020-2023  润新知