2017-02-01 3 views
2

저는 새롭게 추가 된 Flask와 약간의 데이터베이스 모델링에 대해 혼란 스럽습니다. 어떤 의미로든 게시 할 수있는 질문이 아니라면 사과하십시오.데이터베이스 기반 폼 (Flask)

나는 Flask에 다중 선택 모델 필드를 생성해야하며 백엔드 관리 패널에서 값을 설정하기 위해이 필드에 액세스 할 수 있어야합니다. 다중 선택 필드를 작성하는 WTF 양식의 문서 옵션을 표시합니다. 나는 데이터베이스에 첨부 된 양식을 작성하는 방법을 혼동합니다. 내가 Django 사용자이고 Django Forms와 ModelForms가 Flask에 무엇이 될지 이해하려고 시도하기 때문에 다른 누군가가 나를 위해 그것을 정리할 수 있습니까? 어떻게 데이터베이스 기반 양식을 플라스크에 렌더링합니까? 어떻게 데이터베이스를 위해 다중 선택 필드를 만들 수 있습니까? 도와주세요.

답변

2

당신이 찾고있는 것은 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) 

희망이 있습니다.

+0

정말 좋은 설명 방법입니다. 고마워요, 많은 남자! –