[PYTHON] pyramid tutorial notes (single_file_tasks)

single_file_tasks Make a note of what you learned in the tutorial.

download

file organization

File Description
tasks.py python code
schema.sql Initial DB settings sql
tasks.db Store task data
static/style.css css
templates/layout.mako layout
templates/new.mako Task creation
templates/list.mako Task list
templates/notfound.mako 404

main processing


    #Declaration
    settings = {}
    settings['reload_all'] = True
    settings['debug_all'] = True
    settings['mako.directories'] = os.path.join(here, 'templates')
    settings['db'] = os.path.join(here, 'tasks.db')
    #Create session. session is cookie based.(document.You can check it with a cookie.)
    session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')

    #Pour settings into pyramid
    config = Configurator(settings=settings, session_factory=session_factory)
    #Path setting
    config.add_route('list', '/')
    config.add_route('new', '/new')
    config.add_route('close', '/close/{id}')
    #Specifying a static path
    config.add_static_view('static', os.path.join(here, 'static'))
    #Decorator (@view_config and@Find subscriber) and add it to the settings
    config.scan()

    #web server settings
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

pyramid.events.subscriber

Example

Requests are executed first for requests. (preExecute () in synfony) DB connection processing is in progress. The process to disconnect the DB connection at the end of the request is included. (postExecute)

Called only once immediately after the web server is started.

pyramid.httpexceptions.HTTPFound

Redirects to a specific page to prevent double registration by reloading the page.

logging

python


import logging
logging.basicConfig()
log = logging.getLogger(__file__)
log.warn('NewRequest')

@reify

It caches the result of the function and returns only the result without processing after the first time.

pyramid.session

python


  session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
  config = Configurator(settings=settings, session_factory=session_factory)

python


  request.session.flash('Task was successfully reopen!')  #Set value for session
  #template side:
  % if request.session.peek_flash(): #Check if the session has a value
      request.session.pop_flash()     #Show session value
  % endif

sqlite3

select


  rs = request.db.execute("select id, name from tasks where closed = 0")
  tasks = [dict(id=row[0], name=row[1]) for row in rs.fetchall()]

Get only 1 record


    row = rs.fetchone()
    tasks = [dict(id=row[0], name=row[1])]

Refer to the result of select by column name


    request.db = sqlite3.connect(settings['db'])
+   request.db.row_factory = sqlite3.Row

-   tasks = [dict(id=row[0], name=row[1]) for row in rs.fetchall()]
+   tasks = [dict(id=row["id"], name=row["name"]) for row in rs.fetchall()]

update


  task_id = int(request.matchdict['id'])  #Type conversion and set
  #placeholder
  request.db.execute("update tasks set closed = ? where id = ?", (0, task_id))
  request.db.commit()  #It will not be saved unless you commit.

Auto commit ON


    request.db = sqlite3.connect(settings['db'])
    request.db.isolation_level = None
#Or
    request.db = sqlite3.connect(settings['db'], isolation_level = None)

rollback


  request.db.rollback()

pyramid.config.Configurator

Store value in Configurator


mysettings['val'] = "hello"
config = Configurator(settings=mysettings)

Refer to the value stored in Configurator(@subscribers)


request = event.request
settings = request.registry.settings
log.warn(settings['val'])

Refer to the value stored in Configurator(@view)


settings = request.registry.settings
log.warn(settings['val'])

py:development.ini态production.request the value of ini.registry.Store in settings


{'debug_routematch': True, 
 'pyramid.default_locale_name': 'en',
 'db': '/home/user/local/virtualenv/tasks/tasks.db',
 'pyramid.reload_templates': True,
 'debug_templates': True,
 'debug_all': True,
 'reload_templates': True,
 'mako.directories': '/home/user/local/virtualenv/tasks/templates',
 'pyramid.debug_routematch': True,
 'reload_resources': True,
 'default_locale_name': 'en',
 'pyramid.reload_assets': True,
 'reload_all': True,
 'debug_authorization': True,
 'pyramid.debug_authorization': True,
 'pyramid.reload_resources': True,
 'reload_assets': True,
 'pyramid.debug_notfound': True,
 'pyramid.debug_templates': True,
 'prevent_http_cache': False,
 'debug_notfound': True,
 'pyramid.prevent_http_cache': False}

Page 404

python


@view_config(context='pyramid.exceptions.NotFound', renderer='notfound.mako')
def notfound_view(request):
    request.response.status = '404 Not Found'
    return {}

Catch any exceptions

python


@view_config(context=Exception, renderer='exception.mako')
def error_view(exception, request):
    return {'message':exception}

Other

Get the file directory (absolute path)

python


here = os.path.dirname(os.path.abspath(__file__))

Example of use


os.path.join(here, 'schema.sql')
settings['mako.directories'] = os.path.join(here, 'templates')

Recommended Posts

pyramid tutorial notes (single_file_tasks)
pyramid tutorial memo (bank account)
pyramid
A note about doing the Pyramid tutorial