Why write an API

Flask is itself a Web framework, and you can use the Python Flask framework to develop Web pages in an embedded way. Because now all pay attention to a front and back end separation, then why want to front and back end separation, and listen to me slowly. Not all scenarios are suitable, but most projects can be implemented with the separation of the front and back ends. As I am mainly engaged in the front-end development of enterprise-level back-end applications, I personally believe that the advantages of front-end and back-end separation far outweigh the disadvantages for the development of back-end applications. Most of the backend application we can all make a SPA (single page), and the main characteristic is a single page application partial refresh, the routing calls through the front-end control AJAX, the background to provide interface can be achieved, and this way the user experience is more friendly, pages load more quickly, develop and maintain, it reduces the cost of many, efficiency improved significantly. Similarly, the separation of front and back ends is also tried in display websites and mobile APP pages. In the case that the front and back ends are not separated, the server side has to process the Web side separately and return complete HTML, which is bound to increase the complexity of the server side and poor maintainability, while the Web side needs to load complete HTML, which affects webpage performance to a certain extent, which is very unfriendly to the place where the performance of the mobile side is king. With the development of the front-end technology and iteration, the front-end MVC framework arises at the historic moment, using the front end of the current mainstream framework, such as the React, Vue, presents, etc. We can easily construct a render without server can show the site, at the same time this kind of framework provides the front routing functions, the background can no longer control the routing of jump, Throw all the business logic that belongs to the front end to the front end, so that the separation of the front end and the back end can be said to be the most thorough.

preparation

  • python 3
  • Flask, Flask_CORS and other libraries
  • The development tools

Code implementation

# -*- coding: utf-8 -*-
# /usr/bin/python3
from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
import pymysql
import urllib, urllib.request, sys
import ssl
import json
import pprint
# from urllib import parse,request

coon = pymysql.connect(host='127.0.0.1',user='root',password='123456',db='python',autocommit=True)

app = Flask(__name__)


CORS(app, resources=r'/*')
@app.route('/arp',methods=['get'.'post'])
def arp2() :
	header_dict = {'User-Agent': 'the Mozilla / 5.0 (Windows NT 6.1; Trident / 7.0; The rv: 11.0) like Gecko '}
	url='http://rap2api.taobao.org/app/mock/281909/place'
	req = urllib.request.Request(url,headers=header_dict)
	res = urllib.request.urlopen(req)
	res = json.loads(res.read())
	return res
@app.route('/userList',methods=['get'.'post'])
def userList() :
	header_dict = {'User-Agent': 'the Mozilla / 5.0 (Windows NT 6.1; Trident / 7.0; The rv: 11.0) like Gecko '}
	url='http://rap2api.taobao.org/app/mock/281909/userList'
	req = urllib.request.Request(url,headers=header_dict)
	res = urllib.request.urlopen(req)
	res = json.loads(res.read())
	return res

@app.route('/select',methods=['get'.'post'])
def json_contents() :
	global coon
	coon.ping()
	cursor = coon.cursor()
	cursor.execute("select * from asp")
	data = cursor.fetchall()
	return jsonify(data)

@app.route('/miss',methods=['get'.'post'])
def json_miss() :
	try:
		miss = request.form['miss']
	except Exception as e:
		miss = request.args.get('miss')
	global coon
	coon.ping()
	cursor = coon.cursor()
	cursor.execute("select * from asp where id=%s",miss)
	data = cursor.fetchall()
	return jsonify(data)

@app.route('/list',methods=['get'.'post'])
def json_list() :
	try:
		ids = request.form['id']
	except Exception as e:
		ids = request.args.get('id')
	global coon
	coon.ping()
	cursor = coon.cursor()
	cursor.execute("select * from list where flag=%s limit 1",ids)
	data = cursor.fetchall()
	return jsonify(data)

@app.route('/vs',methods=['get'.'post'])
def json_vs() :
	# Access interface
	global coon
	coon.ping()
	cursor = coon.cursor()
	cursor.execute("select * from t_vs")
	data = cursor.fetchall()

	cursor = coon.cursor()
	sql = "update t_vs set vs=%s where id=1"
	cursor.execute(sql,data[0] [1] +1)
	data1 = cursor.fetchall()

	return jsonify(data)




if __name__=="__main__":
	app.run(port=887,debug=True,host='0.0.0.0')
   
Copy the code

The whole project briefly introduces the writing of some basic interfaces. After startup, access the interface through the current IP + port number, the path to access is @app.route(‘ /vs’,methods=[‘ get ‘, ‘POST’]) /vs, for example: 127.0.0.1:887/vs. CORS(app, resources=r ‘/*’) is designed to solve cross-domain problems