flask 学习笔记 mvc ,sqlalchemy(insert,update)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

# 模型类
from sqlalchemy import Column, Integer, String
from application.database.mysqldb import Base

class UserModel(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, id=None, name=None):
        self.id = id
        self.name = name

 

# -*- coding: utf-8 -*-
# 数据库连接类
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("mysql+pymysql://root:[email protected]:3306/test?charset=utf8",
                       convert_unicode=True,
                       echo=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.db_session = db_session
Base.query = db_session.query_property()

def init_db():
    # 在这里导入所有的可能与定义模型有关的模块,这样他们才会合适地
    # 在 metadata 中注册。否则,您将不得不在第一次执行 init_db() 时
    # 先导入他们。
    Base.metadata.create_all(bind=engine)

 

# -*-coding: utf-8 -*-
# 控制器类
from flask import render_template, make_response, jsonify, request, flash
import json
from flask.views import View
from application.models.UserModel import UserModel

class User(View):
    '''
    用户类
    '''
    methods = ['GET', 'POST']

    def dispatch_request(self):
        user = UserModel.query.filter(UserModel.id == 2).first()
        user_obj = {"id":user.id, "name":user.name}
        return jsonify(user_obj)

class UserLogin(View):
    methods = ['GET', 'POST']

    def dispatch_request(self):
        if request.method == 'POST':
            username = request.form['username']
            user = UserModel.query.filter(UserModel.name == username).first()
            if user is None:
                _user_save = UserModel(name=username)
                UserModel.db_session.add(_user_save)
                UserModel.db_session.commit()
                flash(u"登陆失败!")
            else:
                UserModel.query.filter(UserModel.id > 2).update({UserModel.name:'tets2'})
                UserModel.db_session.commit()
                flash(u"登陆成功!")
            return render_template('user/login.html')
        else:
            return render_template('user/login.html')




{% block head %}


{% block title %}{% endblock %} - My Webpage
{% endblock %}

{% with messages = get_flashed_messages() %}
  {% if messages %}
    
    {% for message in messages %}
  • {{ message }}
  • {% endfor %}
{% endif %} {% endwith %}
{% block content %}{% endblock %}
{% block footer %} {% endblock %}

{% extends "common/header.html" %}

{% block head %}
    {{ super() }}
  
{% endblock %}

{% block content %}
  
{% endblock %} {% block footer %} {{ super() }} {% endblock %}

转载于:https://my.oschina.net/phper1234/blog/1498969

你可能感兴趣的:(flask 学习笔记 mvc ,sqlalchemy(insert,update))