flaskは単純なクエリー要求処理とドメイン間


文章のアウトライン
  • flask汎用プロジェクト構造
  • flask概要
  • 本体コードロジック
  • flaskドメイン間問題の処理
  • flaskログ
  • flaskマイクロサービスFlask-RESTful
  • サービスコマンド
  • を起動する.
    flask汎用プロジェクト構造
    | - projectName
    	| - app  //   
    		| - templates //jinjia2  
    		|- static //css,js        
    		| - main  //py    ,        ,         
    			| - __init__.py
    			|- errors.py
    			|- forms.py
    			|- views.py
    		|- __init__.py
    		|- email.py //      
    		|- models.py //     
    	|- migrations //       
    	| - tests  //    
    		|- __init__.py
    		|- test*.py //|- venv  //    
    	|- requirements.txt //|- config.py //|- manage.py //    
    	
    

    flaskの概要
    http://docs.jinkan.org/docs/flask/quickstart.html#a-minimal-application
    マスターコードロジック
    最も簡単なクエリー・サービス・サンプル
    
    #!/usr/bin/env python
    # -*- encoding: utf-8 -*-
    #-------------------------------------------------------------------------------
    '''
    @Author  :   {SEASON}
    @License :   (C) Copyright 2013-2022, {OLD_IT_WANG}
    @Contact :   {[email protected]}
    @Software:   PyCharm
    @File    : 
    @Time    :   2019/4/25 14:57
    @Desc    :
    
    '''
    #-------------------------------------------------------------------------------
    
    import json
    import random
    import logging
    
    from flask import Flask
    
    from flask_sqlalchemy import SQLAlchemy
    from flask import request,Response
    from flask_cors import CORS
    
    
    log_file_str = 'shuanghe_demo.log'
    log_level = logging.INFO
    app = Flask(__name__)
    CORS(app)
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@ip:3306/database'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    
    db = SQLAlchemy(app)
    
    english_chinese_dict = {'id':'    ',
    'name':'  ',
    'sex':'  ',
    'age':'  ',
    }
    
    
    class neihuang_underwriting_search_result(db.Model):
        __tablename__ = 'neihuang_underwriting_search_result'
    
        id = db.Column(db.String(32),primary_key=True)
        name = db.Column(db.String(32))
        sex = db.Column(db.String(32))
        age = db.Column(db.String(32))
        
    
    
        def __repr__(self):
            return '' % self.id
    
    def convert_to_dict(obj):
        ''' Object     Dict  '''
        result_dict = {}
        result_dict.update(obj.__dict__)
        result_dict.pop('_sa_instance_state', None)
        result_dict = random_value_of_labels(result_dict)
        return result_dict
    
    
    
    
    def get_id_result(id):
        result = neihuang_underwriting_search_result.query.filter_by(id=id).one()
    
        result_dict = convert_to_dict(result)
        # result_list = database_name_conversion(result_dict)
        result_json = json.dumps(result_dict,ensure_ascii=False)
        return result_json
    
    
    @app.route('/api/search',methods=['POST','GET'])
    def search():
    
        #result_json  = get_id_result(id)
        if request.method == 'GET':
            user_id = json.loads(''.join(x for x in request.args))['id']
            print(user_id)
            app.logger.info(user_id + ' is search ING .......')
            result_json  = get_id_result(user_id)
    
        return Response(result_json)
    
    
    if __name__ == '__main__':
    
        handler = logging.FileHandler(log_file_str, encoding='UTF-8')
        handler.setLevel(log_level)
        logging_format = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
        handler.setFormatter(logging_format)
        app.logger.addHandler(handler)
    
    
        app.run(debug=True, host='0.0.0.0', port=18081)
        #        
        # CORS(app, supports_credentials=True)
    

    flaskドメイン間問題の処理
    ドメイン間問題を処理する際には、次のコードをグローバル化する必要があります.すなわち、app=Flask(name)cors=CORS(app)を配置します.
    そうでなければ、ドメイン間で問題が発生します.エラーメッセージは次のとおりです.
    Access to XMLHttpRequest at ‘-----’ from origin ‘http://localhost:63342’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
    flaskログ
    https://blog.csdn.net/iszhenyu/article/details/56846551
    flaskマイクロサービスFlask-RESTful
    書き終わったらhttps://flask-restful.readthedocs.io/en/latest/
    サービスコマンドの起動
    参照先:https://www.cnblogs.com/zzyoucan/p/7764590.html nohup command > myout.file 2>&1 &