Домой Edit me on GitHub

2019-03-15

Каналы передачи данных | Сетевое программирование | Базы данных | Основы Веб-программирования

Блог

models.py - данные хранятся в БД SQLite
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- coding: utf-8 -*-
from jinja2.utils import generate_lorem_ipsum
from sqlalchemy import Column, Integer, String, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()


class Articles(Base):
    __tablename__ = 'articles'

    id = Column(Integer, primary_key=True)
    title = Column(String(250), nullable=False)
    content = Column(Text, nullable=False)

    def __repr__(self):
        return "<{}>".format(self.name)


engine = create_engine('sqlite:///foo.db')

Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
dbsession = Session()

for id, article in enumerate(range(100), start=1):
    title = generate_lorem_ipsum(
        n=1,         # Одно предложение
        html=False,  # В виде обычного текста
        min=2,       # Минимум 2 слова
        max=5        # Максимум 5
    )
    content = generate_lorem_ipsum()
    article = Articles(**{'id': id, 'title': title, 'content': content})
    dbsession.add(article)
dbsession.commit()
dbsession.close()
views.py - SQLAlchemy
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# -*- coding: utf-8 -*-
import deform
from jinja2 import Environment, FileSystemLoader
from webob import Request, Response

from common import get_csrf_token, get_session
from models import Session, Articles


env = Environment(loader=FileSystemLoader('templates'))


def wsgify(view):
    def wrapped(environ, start_response):
        request = Request(environ)
        app = view(request).response()
        return app(environ, start_response)
    return wrapped


class BaseArticle(object):

    def __init__(self, request):
        self.request = request
        article_id = self.request.environ['wsgiorg.routing_args'][1]['id']
        dbsession = Session()
        self.article = dbsession.query(Articles).filter_by(id=article_id).one()
        dbsession.close()


class BaseArticleForm(object):

    def get_form(self):
        from forms import CreateArticle
        self.session = get_session(self.request)
        self.session['csrf'] = get_csrf_token(self.session)
        schema = CreateArticle().bind(request=self.request)
        submit = deform.Button(name='submit',
                               css_class='blog-form__button')
        self.form = deform.Form(schema, buttons=(submit,))
        return self.form


@wsgify
class BlogIndex(object):

    def __init__(self, request):
        self.page = request.GET.get('page', '1')
        from paginate import Page
        dbsession = Session()
        articles = dbsession.query(Articles).all()
        self.paged_articles = Page(
            articles,
            page=self.page,
            items_per_page=8,
        )
        dbsession.close()

    def response(self):
        return Response(env.get_template('index.html')
                        .render(articles=self.paged_articles))


@wsgify
class BlogCreate(BaseArticleForm):

    def __init__(self, request):
        self.request = request

    def response(self):
        if self.request.method == 'POST':
            submitted = self.request.POST.items()
            try:
                self.get_form().validate(submitted)
            except deform.ValidationFailure as e:
                return Response(
                    env.get_template('create.html').render(form=e.render()))
            article = Articles(**{'title': self.request.POST['title'],
                                  'content': self.request.POST['content']
                                  })
            dbsession = Session()
            dbsession.add(article)
            dbsession.commit()
            dbsession.close()
            self.session = get_session(self.request).pop('csrf')
            return Response(status=302, location='/')
        return Response(env.get_template('create.html')
                        .render(form=self.get_form().render()))


@wsgify
class BlogRead(BaseArticle):

    def response(self):
        if not self.article:
            return Response(status=404)
        return Response(env.get_template('read.html')
                        .render(article=self.article))


@wsgify
class BlogUpdate(BaseArticle, BaseArticleForm):

    def response(self):
        if self.request.method == 'POST':
            submitted = self.request.POST.items()
            try:
                self.get_form().validate(submitted)
            except deform.ValidationFailure as e:
                return Response(
                    env.get_template('create.html').render(form=e.render()))
            self.article.title = self.request.POST['title']
            self.article.content = self.request.POST['content']
            dbsession = Session()
            dbsession.add(self.article)
            dbsession.commit()
            dbsession.close()
            self.session = get_session(self.request).pop('csrf')
            return Response(status=302, location='/')
        return Response(
            env.get_template('create.html')
            .render(form=self.get_form().render(
                self.article.__dict__)))


@wsgify
class BlogDelete(BaseArticle):

    def response(self):
        dbsession = Session()
        dbsession.delete(self.article)
        dbsession.commit()
        dbsession.close()
        return Response(status=302, location='/')
Previous: Формы Next: Фреймворк Pyramid