"Python" Learning note 5-using flask to mock interfaces

Source: Internet
Author: User

# 1, Mock interface
# import Flask #python的轻量级的开发框架
# # interface, development of backend services
# # in the browser run Http://127.0.0.1:8080/get_user, or other way to access the interface
# server = Flask. Flask (__name__) #__name__当前文件名, take our app Python as a server
# @server. Route ('/get_user ', methods=[' get ', ' post ') #将下面函数变成一个接口
# def Get_all_user ():
# return ' cm interface ' #return只能返回字符串
# #启动服务, plus debug Auto help restart
# Server.run (port = 8080,debug = True)


# 2, call your own module, connect to the database, browser request interface
# import Tools #使用时, need to use Tools.op_mysql ()
From lib.tools import Op_mysql #使用时, directly with Op_mysql ()
# Both of these options are available

3, write the interface to form a standard directory structure, decomposition of the files of each directory

4, start.py run the startup program, start the service here

1 #This is the program's entry file, which will start the service command inside2 3 #add root to environment variable to facilitate directory error at underlying directory execution4 ImportSys,os5Base_path = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))#fetch to API directory, root directory6 Sys.path.insert (0,base_path)7 8 #Add environment variable to import, otherwise the import will be abnormal9  fromLib.mainImportServerTenServer.run (port = 8080,host ='0.0.0.0', debug = True)#The default port number is One #host = ' 0.0.0.0 ' means that everyone in the LAN can access their interfaces via IP

5, setting set general variables, etc.

1 ' x.x.x.x ' 2 ' 123456 ' 3 PORT = 33064'jxz'5'jxz  '

6. main.py ... Own main program

1 #Import Tools #使用时, need to use Tools.op_mysql ()2  fromLib.toolsImportOp_mysql#when used, direct use of op_mysql ()3 #both of these methods can be4 5 ImportFlask,json#a lightweight development framework for Python6 #interface, development of backend services7 #run Http://127.0.0.1:8080/get_user in the browser, or other ways to access the interface8Server = Flask. Flask (__name__)#__name__ The current file name, take our app Python as a server9 Ten  One   #Browser Output Bt_stu The first 5 data in the table A@server. Route ('/get_user', methods=['Get','Post'])#turn the following function into an interface - defGet_all_user (): -sql ='select * from Bt_stu limit 5;' theres = op_mysql (sql =sql) -Response = Json.dumps (res,ensure_ascii=False) -     returnResponse#Return only returns a string -  +  - #browser input User ID, name, insert data into Database Stu table, +@server. Route ('/add_user', methods=['Post'])#What type of interface is supported by the Code A defAdd_user (): atuser_id = Flask.request.values.get ('ID') -user_name = Flask.request.values.get ('u') -sql ="INSERT into Stu values ('%s ', '%s ');"%(User_id,user_name) -     ifuser_id anduser_name: -res = op_mysql (sql =sql) -Response = {"Code":"308","message":"Success"} in     Else: -Response = {"Code":"503","message":"parameter cannot be empty"} to     returnJson.dumps (Response,ensure_ascii=false)#Return only returns a string

7. Tools tool class files, related functions in this area

1 ImportPymysql2  fromConfImportsetting3 4 #1. Operation MySQL5 defop_mysql (SQL):6conn = Pymysql.connect (host=setting. Mysql_host,user=setting. USER,7password=setting. PASSWORD,8port=setting. PORT,9CharSet ='UTF8',Tendb =setting. DB) Onecur = conn.cursor (cursor=pymysql.cursors.DictCursor) A     #determine if commit is required, depending on the type of the Select Update Delete Insert - cur.execute (SQL) -Sql_start = Sql[:6].upper ()#Select is case-insensitive and the first 6 bits are converted to uppercase the     ifSql_start = ='SELECT': -res =Cur.fetchall () -     Else: - Conn.commit () +res ='OK' - cur.close () + conn.close () A     returnRes

"Python" Learning note 5-using flask to mock interfaces

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.