Python 프로젝트-Day 27-token 해석 장식 기-python 연결 mysql

3883 단어 python 프로젝트
Python 프로젝트-Day 27-token 해석 장식 기-python 연결 mysql
  • 장식 기 를 사용 하여 token
    from functools import wraps
    import jwt
    import datetime
    from flask import Blueprint,request
    datetimeInt = datetime.datetime.utcnow() + datetime.timedelta(seconds=180)
    SECRECT_KEY = 'secret'
    def checkToken():
        def decorated(func):
            @wraps(func)
            def wrapper():
    
                try:
                    token=request.headers['token']
                    print('token  :')
                    print(token)
                    decoded = jwt.decode(token, SECRECT_KEY, audience='webkit', algorithms=['HS256'])
                    return func()
                except jwt.ExpiredSignatureError as err:
                    print("erroing.................",err)
                    decoded = {"error_msg": "is timeout !!", "some": None}
                    return '{"code":"004"}'+request.url #       
                except Exception:
                    decoded = {"error_msg": "noknow exception!!", "some": None}
                    print("erroing2.................")
                    return '{"code":"004"}'+request.url
    
            return wrapper
    
        return decorated
    
    
    def jwtEncoding(some, aud='webkit'):
        datetimeInt = datetime.datetime.utcnow() + datetime.timedelta(seconds=180)
        print(datetimeInt)
        option = {
            'iss': 'jobapp.com',
            'exp': datetimeInt,
            'aud': 'webkit',
            'some':some
        }
        encoded2 = jwt.encode(option, SECRECT_KEY, algorithm='HS256')
        print(encoded2.decode())
        return encoded2.decode()
    
    if __name__ == '__main__':
        res=jwtEncoding('{"userid","889"}')
    
        print(res)
    
    을 분석 하고 경로 방법 에서 호출
    @resume_app.route('/add')  #/user/add
    @checkToken()  #          
    def add():
        return '    '
    
  • python 데이터베이스 연결 MySQL
        pymysql
    import pymysql
    #          
    connect = pymysql.connect(host='127.0.0.1', user='root', port=3306, password='', db=database)
          
    cursor=connect.cursor()
    #      sql  
    sql='select * from user'
    #  sql
    cursor.execut(sql)
    #      
    res=cursor.fetchall()
    print(res)
    #    
    cursor.close()
    connect.close()
    
    python 연결 mysql 봉인init__.py
    import pymysql
    def get_connect(database):
        connect = pymysql.connect(host='127.0.0.1', user='root', port=3306, password='', db=database)
        return connect
    
    mysql_connect.py
    from app.dao.__init__ import get_connect
    def test_a(**kwargs):
        print(kwargs)
        sql=''
        for i in kwargs.keys():
            print(i)
            if not sql:
                sql=sql+i
            else:
                sql = sql + ',' + i
        print(sql)
    def create_mysql_connect(database,table,name,psd):
        try:
            connect = get_connect(database)
            cursor = None
    
    
            cursor = connect.cursor()
    
    
            sql = 'INSERT INTO {0} (username,password) VALUES ("{1}","{2}")'.format(table,name,psd)
            print(sql)
            res = cursor.execute(sql)
    
            connect.commit()
        except Exception as ex:
            print(ex)
        finally:
            if cursor:
                cursor.close()
            if connect:
                connect.close()
    
    def select_table(table):
        try:
            connect=None
            cursor=None
            connect = get_connect('test')
            cursor = connect.cursor()
            sql = 'SELECT * from {0}'.format(table)
            cursor.execute(sql)
            res=cursor.fetchall()
            return res
        except Exception as ex:
            print(ex)
        finally:
            if cursor:
                cursor.close()
            if connect:
                connect.close()
    
  • 좋은 웹페이지 즐겨찾기