喜欢《千与千寻》中的一句话,不管前方的路有多苦,只要走的方向正确,不管多么崎岖不平,都比站在原地更接近幸福。
分享一个flask搭建的小web
1 # -*- coding: utf-8 -*- 2 from flask import Flask 3 from flask import request 4 import os,re,io 5 from flask_restful import Api 6 from flask_restful import Resource,reqparse 7 8 9 app = Flask(__name__) 10 api = Api(app) 11 12 class BaseResource(Resource): 13 def __init__(self): 14 Resource.__init__(self) 15 self.parser = reqparse.RequestParser() 16 self.add_args() 17 self.create_args() 18 def add_args(self): 19 pass 20 def add_argument(self,*args,**kwargs): 21 self.parser.add_argument(*args,**kwargs) 22 def create_args(self): 23 self.args = self.parser.parse_args() 24 def get_arg(self,key): 25 return self.args[key] 26 27 class HelloWorld(BaseResource): 28 def add_args(self): 29 self.add_argument('param',type=str,help='Param') 30 def say(self): 31 param=self.get_arg("param") 32 return re_result(msg="Hello World", code=0,data=param) 33 def post(self): 34 return self.say() 35 def get(self): 36 return self.say() 37 38 def re_result(msg="", data=None, code=-1): 39 return {"msg": msg, "data": data, "code": code} 40 41 42 43 @app.route('/') 44 def hello_world(): 45 return 'Hello World!' 46 47 48 49 @app.route("/index") 50 def hello_index(): 51 title='后台返回前端页面参数'52
return render_template('index.html',title=title) 53 54 55 api.add_resource(HelloWorld,'/helloworld') 56 57 if __name__ == '__main__': 58 app.run(debug=True,port=8888)
请求 http://localhost:8888/ 返回 "Hello World!"
请求 http://localhost:8888/index 返回静态页面 (注意静态资源存放位置)
请求 http://localhost:8888/helloworld?param=test 返回 {"msg": "Hello World", "data": "test", "code": 0} json字符串