flask初次搭建rest服务笔记

官网中有用的记录一下,太多只是记录了最简单的
官网docs:http://flask.pocoo.org/docs/0.12/

跑起来一个程序

$ export FLASK_APP=hello.py
$ flask run
* Running on http://127.0.0.1:5000/
$ python -m flask run
* Running on http://127.0.0.1:5000/

#监听所有ip

flask run --host=0.0.0.0

# debug 永远不要用在生产环境

$ export FLASK_DEBUG=1
$ flask run

#路径中有参数的使用

@app.route('/post/<int:post_id>')
@app.route('/user/<username>')

string accepts any text without a slash (the default)
int accepts integers
float like int but for floating point values
path like the default but also accepts slashes
any matches one of the items provided
uuid accepts UUID strings

#http.method

from flask improt request
@app.route('/user/<username>', methods=['GET', 'POST'])
if request.method == 'GET':......

#render render_template会找templates文件夹下的hello.html,把参数传过去

from flask import render_template
@app.route('/hello')
@app.route('/hello/<name>')
def greeting(name=None):
return render_template('hello.html', name=name)

#路径中?后的参数的获取
@app.route('/search', methods=['GET'])

def search():
  word = request.args.get('key','')
  return 'key word is: %s' % word
http://localhost:5000/search?key=value  #浏览器输入访问

 

#获取前台post请求发过来的json格式的数据

import json
@app.route('/login', methods=['POST'])
def login():
  return json.loads(request.data)['name']

 

#log  

app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')

 

#错误处理

@app.errorhandler(404)
def page_notfound(error):
  return render_template('not_found.html'), 404
@app.errorhandler(404)
def not_found(error):
  resp = make_response(render_template('not_found.html'), 404)
  resp.headers['X-Something'] = 'A value'
  return resp

 

#捕获自定义异常处理

class RunException(RuntimeError):
def __init__(self, msg, code):
  self.msg = msg
  self.code = code
@app.errorhandler(RunException)
def exce(error):
  return 'ERROR[msg: %s, code: %d]' % (error.msg, error.code), error.code
@app.route('/exce', methods=['GET'])
def test_e():
  raise RunException('occur', 1001)
  return 'no error'

 

#配置文件
#http://flask.pocoo.org/docs/0.12/config/

app = Flask(__name__)
app.config['DEBUG'] = True
app.debug = True
app.config.update(
DEBUG=True
SECRET_KEY='value' 
)
app.config.from_object('yourapplication.default_settings_OR_class')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')

class Config(object):
  DEBUG = False
  TESTING = False
  DATABASE_URI = 'sqlite://:memory:'
class ProductionConfig(Config):
  DATABASE_URI = 'mysql://user@localhost/foo'
app.config.from_object('configmodule.ProductionConfig')

 

#命令行和执行代码里的方法
#http://flask.pocoo.org/docs/0.12/cli/

import click
@app.cli.command()
def initdb():
  """Initialize the database."""
  click.echo('Init the db')
$ flask initdb
Init the db
@app.cli.command(with_appcontext=False) #命令行失效
def example():
  pass

 

sqlacodegen:从已有的数据库中的表导出module(听这个官网说好像这个是sqlautocode的加强版,sqlautocode有bug)

pip install sqlacodegen
#使用方法    sqlacodegen --help查看使用方法
sqlacodegen --outfile /home/ito/workspace1/ZPyService/src/py_service/module.py mysql://root:root@localhost:3306/fzk

SQLAlchemy:orm
http://docs.sqlalchemy.org/en/rel_1_1/orm/tutorial.html

pip install SQLAlchemy             #安装
pip uninstall SQLAlchemy           #卸载
pip install SQLAlchemy==<version>      #安装指定版本

使用

  db = create_engine(<DB_URI>, echo=True)
  session = sessionmaker(bind=db)()
  #或者*******************************
  Session = sessionmaker()
  Session.configure(bind=engine)
  *************************************
session.query(module.User).filter_by(username='bar').first()
  session.add(a_user)
  session.commit()
 session.add_all([])
 session.dirty
session.new
 session.rollback()
 session.query(User).filter(User.name.in_(['ed', 'fakeuser'])).all()
  for instance in session.query(User).order_by(User.id):
  print(instance.name, instance.fullname)
  for name, fullname in session.query(User.name, User.fullname):
     print(name, fullname)
 for row in session.query(User, User.name).all():
    print(row.User, row.name)
 for row in session.query(User.name.label('name_label')).all():
    print(row.name_label)
  from sqlalchemy.orm import aliased
 user_alias = aliased(User, name='user_alias')
 for row in session.query(user_alias, user_alias.name).all():
    print(row.user_alias)
#分页
for u in session.query(User).order_by(User.id)[1:3]:   print(u)
for name, in session.query(User.name).filter_by(fullname = 'Ed Jones'):
    print(name)
for name, in session.query(User.name).filter(User.fullname == 'Ed Jones'):
print(name)
for user in session.query(User).filter(User.name=='ed').filter(User.fullname=='Ed Jones'):
query.filter(User.name.like('%ed%'))
query.filter(User.name.ilike('%ed%'))  #case-insensitive LIKE
query.filter(User.name.in_(['ed', 'wendy', 'jack']))
query.filter(User.name.in_(
    session.query(User.name).filter(User.name.like('%ed%'))
))
# not in
query.filter(~User.name.in_(['ed', 'wendy', 'jack']))
# is null
query.filter(User.name == None) query.filter(User.name.is_(None))
# is not null
query.filter(User.name != None) query.filter(User.name.isnot(None))
#and
# use and_()    Make sure you use and_() and not the Python and operator! from sqlalchemy import and_ query.filter(and_(User.name == 'ed', User.fullname == 'Ed Jones')) # or send multiple expressions to .filter() query.filter(User.name == 'ed', User.fullname == 'Ed Jones') # or chain multiple filter()/filter_by() calls query.filter(User.name == 'ed').filter(User.fullname == 'Ed Jones')
#or
from sqlalchemy import or_
query.filter(or_(User.name == 'ed', User.fullname == 'Ed Jones'))

  .all() 
 .first()
  .one()  #多余一个或没有会报错
  .one_or_none()
  .scalar()       #i
nvokes the one() method, and upon success returns the first column of the row:

 

 #count
from
sqlalchemy import func
session.query(func.count(User.name), User.name).group_by(User.name).all()
session.query(func.count('*')).select_from(User).scalar()

#join
for u, a in session.query(User, Address).\ ... filter(User.id==Address.user_id).\ ... filter(Address.email_address=='jack@google.com').\ ... all():
session.query(User).join(Address).\
...         filter(Address.email_address=='jack@google.com').\
...         all()
query.join(Address, User.id==Address.user_id)    # explicit condition
query.join(User.addresses)                       # specify relationship from left to right
query.join(Address, User.addresses)              # same, with explicit target
query.join('addresses')     
query.outerjoin(User.addresses) # LEFT OUTER JOIN
#一对多  多条数据从一次查询获取
from sqlalchemy.orm import aliased >>> adalias1 = aliased(Address) >>> adalias2 = aliased(Address) for username, email1, email2 in \ ... session.query(User.name, adalias1.email_address, adalias2.email_address).\ ... join(adalias1, User.addresses).\ ... join(adalias2, User.addresses).\ ... filter(adalias1.email_address=='jack@google.com').\ ... filter(adalias2.email_address=='j25@yahoo.com'): ... print(username, email1, email2)
#exist() 
>>> from sqlalchemy.sql import exists >>> stmt = exists().where(Address.user_id==User.id) >>> for name, in session.query(User.name).filter(stmt):
 

 

 

flask-restful-swagger-2: https://github.com/swege/flask-restful-swagger-2.0
flask-restful-swagger   : https://github.com/rantav/flask-restful-swagger

posted @ 2017-02-10 17:13  bad_boy_f  阅读(2387)  评论(1编辑  收藏  举报