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

# 模型类
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:123456@127.0.0.1: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')
<!--视图文件公共模版-->
<!doctype html>
<html>
<head>
{% block head %}
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="{{ url_for('static', filename='bootstrap-3.3.7-dist/css/bootstrap.min.css') }}">
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
</head>
<body>
  <div id="content">{% block content %}{% endblock %}</div>
  {% block footer %}
  <div id="footer">
    &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.
    <script src="{{ url_for('static', filename='plugins/jquery/jQuery-2.1.4.min.js') }}"></script>
    <script src="{{ url_for('static', filename='bootstrap-3.3.7-dist/js/bootstrap.min.js') }}"></script>
  </div>
  {% endblock %}
</body>
</html>
<!-- 视图文件(子模版)-->
{% extends "common/header.html" %}

{% block head %}
    {{ super() }}
  <style type="text/css">
    .important { color: #336699; }
  </style>
{% endblock %}

{% block content %}
  <form class="form-horizontal" method="post">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">用户名</label>
    <div class="col-sm-10">
      <input name="username" type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
    <div class="col-sm-10">
      <input name="password" type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">登录</button>
    </div>
  </div>
</form>
{% endblock %}

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值