当前位置:   article > 正文

flask_sqlalchemy 搭建flask项目指南(一)

' % self.name

1 app.py

  1. # coding=utf-8
  2. from __future__ import print_function
  3. from flask import Flask
  4. from flask import Flask, jsonify, request, abort
  5. from flask_cors import CORS
  6. from werkzeug.security import safe_str_cmp
  7. app = Flask(__name__, static_folder='/data/www/web/static')
  8. app.debug = True
  9. CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
  10. # 数据库基本配置
  11. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@127.0.0.1:3306/shop_agent'
  12. # 动态追踪修改设置,如未设置只会提示警告
  13. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
  14. # 查询时会显示原始SQL语句
  15. # app.config['SQLALCHEMY_ECHO'] = True
  16. # 连接池个数
  17. app.config['SQLALCHEMY_POOL_SIZE'] = 10
  18. from models import db
  19. db.init_app(app)
  20. from views import *
  21. # 随意无权限路由,简单检查是否正常部署
  22. app.add_url_rule('/user/helloworld', view_func=helloworld, methods=['GET'])
  23. app.add_url_rule('/user/deletedb', view_func=delete_db, methods=['GET'])
  24. app.add_url_rule('/user/initdb', view_func=init_db, methods=['GET'])
  25. if __name__ == "__main__":
  26. app.run(host="0.0.0.0", port=9000, debug=True)

2 models.py

  1. # coding=utf-8
  2. from datetime import datetime
  3. from flask_sqlalchemy import SQLAlchemy
  4. db = SQLAlchemy()
  5. class User(db.Model):
  6. id = db.Column(db.Integer, primary_key=True)
  7. username = db.Column(db.String(80), unique=True)
  8. email = db.Column(db.String(120), unique=True)
  9. category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
  10. # build foreign key relation
  11. category = db.relationship('Category', backref=db.backref('users', lazy='dynamic'))
  12. created_at = db.Column(db.DateTime, default=None)
  13. updated_at = db.Column(db.DateTime, default=None)
  14. deleted_at = db.Column(db.DateTime, default=None)
  15. created = db.Column(db.DateTime)
  16. def __init__(self, username, email, category, category_id, created_at=None, updated_at=None, deleted_at=None):
  17. self.username = username
  18. self.email = email
  19. self.category_id = category_id
  20. self.category = category
  21. if updated_at is None:
  22. updated_at = datetime.utcnow()
  23. if created_at is None:
  24. created_at = datetime.utcnow()
  25. self.updated_at = updated_at
  26. self.created_at = created_at
  27. self.deleted_at = deleted_at
  28. def __repr__(self):
  29. return '<User %r>' % self.username
  30. class Category(db.Model):
  31. id = db.Column(db.Integer, primary_key=True)
  32. name = db.Column(db.String(50))
  33. def __init__(self, name):
  34. self.name = name
  35. def __repr__(self):
  36. return '<Category %r>' % self.name

3 views.py

  1. # coding=utf-8
  2. import sys
  3. import os
  4. import stat
  5. import re
  6. import datetime
  7. import json
  8. import functools
  9. import time
  10. import mimetypes
  11. import uuid
  12. import random
  13. from flask import request
  14. from flask import Flask, jsonify, request, abort, make_response
  15. from flask import send_file, send_from_directory
  16. from werkzeug.utils import secure_filename
  17. from werkzeug.security import generate_password_hash, check_password_hash
  18. from auth.auth import Auth
  19. from utils import trueReturn, falseReturn, formalReturn, get_ip_info
  20. from aliyunapi.dysms_python.demo_sms_send import send_sms
  21. from settings import UPLOAD_PATH, DOWNLOAD_PATH, LOG_PATH, MONGO_URL, FILENAME, ERROR_FILENAME
  22. from log_shop_agent import log, errlog
  23. from models import db, Category, User
  24. def helloworld():
  25. """
  26. :return:
  27. """
  28. message = "hello world!\n developer: victor\n version: 1.0"
  29. return jsonify(message)
  30. def init_db():
  31. ret = db.create_all()
  32. category_python = Category(name='Python')
  33. user = User(username='victor', email='bailuzhou163@163.com', category_id=category_python.id, category=category_python)
  34. db.session.add(category_python)
  35. db.session.add(user)
  36. db.session.commit()
  37. users = category_python.users.all()
  38. user_category = user.category.name
  39. log.logger.info("users: {users}".format(users=users))
  40. log.logger.info("user_category: {user_category}".format(user_category=user_category))
  41. return jsonify(ret)
  42. def delete_db():
  43. ret = db.drop_all()
  44. return jsonify(ret)
4 sqlalchemy的外键建立
基本结构(看models.py):
 1 class User(db.Model):
 2     id = db.Column(db.Integer, primary_key=True)
 3     username = db.Column(db.String(80), unique=True)
 4     email = db.Column(db.String(120), unique=True)
 5     category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
 6 
 7     # build foreign key relation
 8     category = db.relationship('Category', backref=db.backref('users', lazy='dynamic'))
 9 
10     created_at = db.Column(db.DateTime, default=None)
11     updated_at = db.Column(db.DateTime, default=None)
12     deleted_at = db.Column(db.DateTime, default=None)
13 
14     created = db.Column(db.DateTime)
15 
16     def __init__(self, username, email, category, category_id, created_at=None, updated_at=None, deleted_at=None):
17         self.username = username
18         self.email = email
19 
20         self.category_id = category_id
21         self.category = category
22 
23 
24         if updated_at is None:
25             updated_at = datetime.utcnow()
26         if created_at is None:
27             created_at = datetime.utcnow()
28         self.updated_at = updated_at
29         self.created_at = created_at
30         self.deleted_at = deleted_at
31 
32     def __repr__(self):
33         return '<User %r>' % self.username
34 
35 
36 class Category(db.Model):
37     id = db.Column(db.Integer, primary_key=True)
38     name = db.Column(db.String(50))
39 
40     def __init__(self, name):
41         self.name = name
42 
43     def __repr__(self):
44         return '<Category %r>' % self.name

 

如何建立外键关联:

对用户进行分类,用户要关联分类表,用户表要建立关于分类的关联,被关联的分类表什么都不用做:

category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
category = db.relationship('Category', backref=db.backref('users', lazy='dynamic'))

注意事项:

category_id=初始化必填字段是category.id
category=Category对象
ForeignKey('category.id')里的是Category表的小写

关联要写大写表relationship-'Category'
category对象查询反向查询关联用户的时候用users,即category_obj.users.all()
user正向查询关联分类就用user.category.name

 

转载于:https://www.cnblogs.com/adamans/articles/10256493.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/632557
推荐阅读
相关标签
  

闽ICP备14008679号