당신이 찾고있는 것은 SQLAlchemy 내장 ORM으로 모델에서 양식을 만들거나 데이터베이스에 통합되었습니다. 필요한 경우 Flask ORM의 한계를 극복하는 다른 옵션이 있습니다. 다음은 명확성을주는 예제입니다.
from flask import Flask, render_template, redirect, flash
from flask.wtf import Form
from flask.ext.sqlalchemy import SQLAlchemy
from wtf.ext.sqlalchemy.orm import model_form
app=Flask(__app__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/employees.sqlite'
app.config['SQLALCHEMY_ECHO'] = True
# Here you initiate the ext
db=SQLAlchemy(app)
#Let's define a model
class Employee(db.Model)
__tablename__ = 'employee'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False
birthday = db.Column(db.Date, nullable=False
def __repr__(self):
return 'employee %s' %self.name
# Now go to your shell inside your env not in gloabal shell outside your env and run this command.
# From your .py file where you've created all above configration first make an import to db from shell
from file.py import db
#Then create a database with following command in shell
db.create.all()
#Your auto generated database based form below
EmployeeForm() = model_form(Employee, base_class=Form, field_args{'name':{'class':'employee'}})
#Let's create a view with model_form or database based form in your case.
@app.route('/', methods=['GET', 'POST'])
def index()
#request.POST does same in Django or any other Python based web framework like Bottle, Tornado etc
form = EmployeeForm()
try:
if form_validate_on_submit():
employee=Employee() #load the model values
form.populate_obj(Employee) #populates the form with respective values
db.session.add(employee) #gathers the session based data to be added in DB
db.session.commit() #Adds data to DB
flash('New Employee added to database successfully.') #Display a message to end user at front end.
retrun redirect('/') # redirects upon success to your homepage.
except Exception e:
# logs the errors
db.session.rollback()
flash('There was a problem registering new employee. Please contact the site administrator at [email protected]')
employee_list = Employe.query.all() #equailent to django style "item.objects.all() to show list of all existing items.
return render_template('index.html', form=form, employee_list=employee_list)
마지막 줄에는 세 가지가 있습니다. Django에서와 같이 양식 변수 또는 컨텍스트 변수가 "form"
인 경우 최종 사용자가 데이터를 입력 할 수 있습니다. 그러면 데이터베이스에 "employee_list=employee_list"
이라는 이름으로 저장되어 모든 목록을 일반 사용자에게 표시하는 모델 데이터를 갖게됩니다. "flash"
은 Django 메시징 프레임 워크와 같습니다.
다중 선택을 위해 그 모델은 아래와 같은 키 값을위한 djagno 선택 인자와 같습니다 : 필자의 경험에 비추어 볼 때 파이썬 연결 데이터베이스에 대한 간단한 ORM을 "peewee"로 설치하도록 제안합니다.
choices = (('key', 'value')('key', 'value'))
employee_type = db.Model(db.String(90), choices=('key1', 'key2)
희망이 있습니다.
정말 좋은 설명 방법입니다. 고마워요, 많은 남자! –