Django와 flask

Embed Size (px)

Citation preview

Django Flask

(Freelancer)

[email protected]

0. ( )1. 2. Django Flask 3. Django Form WTForms4. Django Flask 5. Django Flask Route 6. Django Flask 7. Django Flask 8. Django Flask URL 9. Django Flask , Reusable Component10.

0. ( )

& & Python 2.x, 3.x = virtualenv& Python 3.x = pyvenv& Virtualenv = Virtualenvwrapper

..Conda, pyenv, autoenv

Django:$ django-admin startproject

Flask:$ mkdir -p project_name/project_name$ touch project_name/project_name/__init__.py

Django Flask

Django:- CBV(Class Based Views)- FBV(Function Based Views)

Flask:- Pluggable View(View, MethodView)- Function View

Django Flask

Django:- CBV(Class Based Views)

Examplefrom django.conf.urls import urlfrom django.views.generic import TemplateView

urlpatterns = [ url(r'^about/$', TemplateView.as_view(template_name="about.html")),]

Django Flask

Django:- FBV(Function Based Views)

Examplefrom django.http import HttpResponseimport datetime

def current_datetime(request): now = datetime.datetime.now() html = "It is now %s." % now return HttpResponse(html)

from django.conf.urls import urlfrom . import viewsurlpatterns = [ url(r'^datetime/$', views.current_datetime)]

Django Flask

Flask View:- Pluggable View(View)

Examplefrom flask.views import View

class ShowUsers(View):

def dispatch_request(self): users = User.query.all() return render_template('users.html', objects=users)

app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))

Django Flask

Flask View:- Pluggable View(Method View)

Exampleclass UserAPI(MethodView): decorators = [user_required] def get(self, user_id): pass

def post(self): # create a new user pass

def delete(self, user_id): # delete a single user pass

Django Flask

Flask View:- Function Based View

[email protected]('/users/')def show_users(page): users = User.query.all() return render_template('users.html', users=users)

Django Form WTForms

Django Models Template

ExampleModel:from django.db import models

class Question(models.Model): tag = models.CharField(max_length=200)

Template:{{ form.tag.label_tag }} {{ form.tag }}

Django Form WTForms

WTForms

Examplefrom wtforms import Form, StringField, validators

class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)])

Django Form WTForms

WTForms

Example{% macro render_field(field) %} {{ field.label }} {{ field(**kwargs)|safe }} {% if field.errors %}

  • {% for error in field.errors %}
  • {{ error }} {% endfor %}

{% endif %} {% endmacro %}

Django Flask

Django $ django-admin startproject $ cd project_name$ ./manage.py startapp

Flask $ mkdir -p /$ touch //__init__.py

1) Blueprint 2) url

Django Flask Route

Django:urls.py

urlpatterns urlpatterns = [ url(r'^datetime/$', views.current_datetime)]

Flask:function: app.add_url_rule, app.register_blueprintdecorator: app.route

Django Flask

DjangoModel Filefrom django.db import models

class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)

Result: CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL);

Django Flask

Flask - Database Filefrom sqlalchemy import create_enginefrom sqlalchemy.orm import scoped_session, sessionmakerfrom sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))Base = declarative_base()Base.query = db_session.query_property()

def init_db(): import yourapplication.models Base.metadata.create_all(bind=engine)

Django Flask

Flask - Model Filefrom sqlalchemy import Column, Integer, Stringfrom yourapplication.database import Base

class User(Base): __tablename__ = 'users' first_name = Column(String(30), nullable=False) last_name = Column(String(30), nullable=False)

Django Flask

Djangofrom django.core.exceptions import ValidationErrorfrom django.utils.translation import ugettext_lazy as _

def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, )

from django.db import models

class MyModel(models.Model): even_field = models.IntegerField(validators=[validate_even])

Django Flask

Django - View

form = MyModel(request.POST)

: form.is_valid() : form.cleaned_data : form.erros

Flask - View form = MyModel(request.form): form.validate() : populate_obj : form.erros

Django Flask URL

DjangoBackend: reverse, reverse_lazy Template: {% url %}

FlaskBackend Template url_for(end_point, **kwargs)

Django Flask , Reusable Component

Django- Custom Tag- Custom Filter

Flask Filter- Custom Tag(, Extension )- Custom Filter- Reusable Component(macro)

Django Flask , Reusable Component

Django - Custom Tag

from django import template

register = template.Library()

@register.simple_tagdef my_tag(a, b, *args, **kwargs): warning = kwargs['warning'] profile = kwargs['profile'] ... return ...

Django Flask , Reusable Component

Django - Custom Filter

from django import template

register = template.Library()

@register.filter(is_safe=True)def add_xx(value): return '%sxx' % value

Django Flask , Reusable Component

Flask - Custom Filter, Global Function

@app.template_filter('filter_name')def int_add(d, b): return d+b

@app.template_global('global_name')def int_minus(d, b): return d-b

Flask - Custom [email protected]_processor def utility_processor(): return dict(name='fastcampus')

Django Flask , Reusable Component

Flask Reusable Component (Macro)

{% macro input(name, value='', type='text', size=20) -%} {%- endmacro %}

{{ input('tt') }}

1) - Flask test_client - travis-CI, Jenkins-CI

2) - (ex, Gitlab, BitBucket )

3) - ( -, , )

4)

PC

.

Thanks

2016.07.08

Django Flask