Python Pyramid – Useful Resources

Python Pyramid – Useful Resources ”; Previous Next The following resources contain additional information on Python Pyramid. Please use them to get more in-depth knowledge on this. Useful Links on Python Pyramid Python Pyramid − Official Website Python Pyramid. Python Pyramid Wiki − Wikipedia Reference for Python Pyramid. Useful Books on Python Pyramid To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Python Pyramid – Discussion

Discuss Python Pyramid ”; Previous Next Pyramid is an open source, WSGI compliant web framework written in Python. Initially the project named as Pylons, but later released under the new name Pyramid. Apart from Pyramid, the Pylons Project consists of different web application technologies such as Waitress (a WSGI server), SubstanceD (Pyramid-based application server), WebOb (a WSGI request/response library), and many more. Print Page Previous Next Advertisements ”;

Command Line Pyramid

Python Pyramid – Command Line Pyramid ”; Previous Next The Pyramid library has a scripts subpackage, and it contains a number of Python scripts that are made available to control and inspect a Pyramid application. These modules can be used both as an importable module as well as from command prompt. Hence, they are often called as command line scripts. These command line scripts are − pserve − serves a web application that uses a PasteDeploy configuration file. pviews − Displaying Matching Views for a Given URL. pshell − The Interactive Shell. proutes − Displaying All Application Routes. ptweens − Displaying “Tweens”. prequest − Invoking a Request. pdistreport − Showing All Installed Distributions and Their Versions. All these command line scripts use the PasteDeploy configuration file (development.ini). pserve This is the most important script. The Pyramid application configured in the “development.ini” [app:main] section is served with the help of the chosen server (Waitress) and the mentioned host and port (localhost:6543). Assuming that the Pyramid project (testproj) is created in the folder of the same name in the Pyramid virtual environment, the following command starts listening to incoming browser requests − Env>..scriptspserve development.ini The pserve module (as also the other Pyramid command-line scripts) can be run as an argument of Python interpreter in the command prompt. Env>python -m pyramid.scripts.pserve development.ini Starting server in PID 1716. 2022-06-23 14:13:51,492 INFO [waitress:485][MainThread] Serving on http://[::1]:6543 2022-06-23 14:13:51,492 INFO [waitress:485][MainThread] Serving on http://127.0.0.1:6543 To make pserve utility more flexible, the following command line parameters can be used − config_uri − The URI to the configuration file. -n <name> − Load the named application (default main). -s <server_type> − Use the named server. –server-name <section_name> − Use the named server as defined in the configuration file (default: main) –reload − Use auto-restart file monitor. -b − Open a web browser to the server url. The application is served at http://localhost:6543 in which case, the access is restricted such that only a browser running on the same machine. If you want to let the other machines on the same network, then edit the “development.ini” file, and replace the listen value in the [server:main] section as shown below − [server:main] use = egg:waitress#main listen = *:6543 The setting *:6543 is equivalent to 0.0.0.0:6543 [::]:6543, as a result, the application responds to requests on all IP addresses possessed by your system, not just requests to localhost. The –reload option in the pserve command line causes the application to be reloaded automatically whenever the running code is modified. Start the application with –reload option. pserve development.ini –reload Starting monitor for PID 36224. Starting server in PID 36224. Serving on http://localhost:6543 Serving on http://localhost:6543 If any change to the project”s .py files or .ini files is made, the server restart automatically − testproj/development.ini changed; reloading … Gracefully killing the server. Starting monitor for PID 36286. Starting server in PID 36286. Serving on http://localhost:6543 Serving on http://localhost:6543 pviews The pviews command line script is used in the command terminal window to print a summary of matching routes and views for a given URL. The pviews command accepts two arguments. The first argument is the path to your application”s “.ini” file and section name inside it. This should be of the format config_file#section_name (default value is main). The second argument is the URL to test for matching views. Let us pviews command with the development.ini file in our testproj project built earlier with Cookiecutter. Env>..scriptspviews development.ini / URL = / context: <pyramid.traversal.DefaultRootFactory object at 0x000001DD39BF1DE0> view name: Route: —— route name: home route pattern: / route path: / subpath: View: —– testproj.views.default.my_view The output shows the requested URL at the top and below which all the matching views are displayed with their view configuration details. In this example only one view matches, so there is just a single View section. pshell The pshell script makes it possible to interact with the Pyramid application”s environment from Python prompt. This shell uses the PasteDeploy configuration file i.e. development.ini as a command line argument (like the other Pyramid scripts) and opens up Python interactive shell. Env>..scriptspshell development.ini Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32 Type “help” for more information. Environment: app The WSGI application. dbsession <sqlalchemy.orm.session.Session object at 0x0000020E9F1452D0> models <module ”testproj.models” from ”f:\pyram-env\testproj\testproj\models\__init__.py”> registry Active Pyramid registry. request Active request object. root Root of the default resource tree. root_factory Default root factory used to create `root`. tm Single-thread implementation of `~transaction.interfaces.ITransactionManager`. >>> The script reads the configuration and the objects declared in it are made available as Python objects to interact with. We can inspect their behaviour from the Python prompt. >>> root <pyramid.traversal.DefaultRootFactory object at 0x0000020E9E2507F0> >>> registry <Registry testproj> The registry settings are read from “development.ini” into a dictionary. We can traverse its contents using the for loop − >>> for k,v in registry.settings.items(): … print (k,”:”,v) … pyramid.reload_templates : True pyramid.debug_authorization : False pyramid.debug_notfound : False pyramid.debug_routematch : False pyramid.default_locale_name : en pyramid.includes : pyramid_debugtoolbar sqlalchemy.url : sqlite:///…testproj/testproj.sqlite retry.attempts : 3 tm.manager_hook : <function explicit_manager at 0x000001D9E64E4550> It is even possible to interact with the database with the help of SQLAlchemy model declared in models.py. The application database is initialized in the beginning when we first complete the cookiecutter steps. We find a models table in the “testproj.sqlite” database with one record in it. We now access this table from the Python prompt as under − >>> m=models.MyModel >>> obj=dbsession.query(m).get(1) >>> obj <testproj.models.mymodel.MyModel object at 0x0000020E9FD96DA0> >>> obj.name ”one” Let us adda new row in the models table. First declare an object

Python Pyramid – Project Structure

Python Pyramid – Project Structure ”; Previous Next As mentioned earlier, the outer testproj folder contains testproj and test packages. In addition, it has other files used to describe, run, and test the application. These files are − MANIFEST.in contains list of files to be included in a source distribution of the package. development.ini is a PasteDeploy configuration file that can be used to execute your application during development. production.ini is a PasteDeploy configuration file that can be used to execute your application in a production configuration. pytest.ini is a configuration file for running tests. setup.py is the standard Setuptools setup.py file used to test and distribute the application. testing.ini is a configuration file used to execute the application”s tests. The “.ini” files are the configurations used by Cookiecutter utility to generate the Pyramid application structure. These filesuse a system called PasteDeploy, which has been developed by Ian Bicking. This library is installed automatically along with Pyramid. Although a Pyramid application can be developed without PasteDeploy support, it gives a standardized way of starting, debugging and testing the application. The predefined settings are read from the configuration files (with .ini extension). These files contain mainly the application configuration settings, server settings and logging settings. development.ini As shown earlier, the Pyramid application built with Cookiecutter is invoked by the following command − pserve development.ini The development.ini contains the PasteDeploy configuration specifications of the application. The configuration specifications in this file are having various sections such as [app:main], [server:main], [loggers] etc. The most important section id [app:main]. It specifies the starting point of the application. [app:main] use = egg:testproj pyramid.reload_templates = true pyramid.debug_authorization = false pyramid.debug_notfound = false pyramid.debug_routematch = false pyramid.default_locale_name = en pyramid.includes = pyramid_debugtoolbar sqlalchemy.url = sqlite:///%(here)s/testproj.sqlite retry.attempts = 3 The very first entry “use = egg:testproj” indicates the name of the Pyramid WSGI application object main. It is declared in the __init__.py file of the textproj package (inside the testproj project folder). This section contains other startup time configuration settings. For instance, the “pyramid.includes” setting specifies the packages to be included in the runtime. In the above example, the debugtoolbar package is included so that the debug panel gets activated when the Pyramid logo is clicked. We have seen its functioning in the earlier section. We also see that the URL of the database to be used in this application has also been specified. The [server:main] section specifies the configuration of a WSGI server which listens on TCP port 6543. It is configured to listen on localhost only (127.0.0.1). [server:main] use = egg:waitress#main listen = localhost:6543 Other various logging related sections use Python”s logging library. These “.ini” file sections are passed to the logging module”s config file configuration engine. production.ini This file used to serve the application instead of the “development.ini” when the application is deployed in the production mode. Both these files are similar. However, in “production.ini”, the debug toolbar is disabled, the reload options are disabled and turns off the debugging options. Here”s a stripped-down version of typical “production.ini” file − [app:main] use = egg:testproj pyramid.reload_templates = false pyramid.debug_authorization = false pyramid.debug_notfound = false pyramid.debug_routematch = false pyramid.default_locale_name = en sqlalchemy.url = sqlite:///%(here)s/testproj.sqlite retry.attempts = 3 [pshell] setup = testproj.pshell.setup [alembic] script_location = testproj/alembic file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s [server:main] use = egg:waitress#main listen = *:6543 [loggers] keys = root, testproj, sqlalchemy, alembic [handlers] keys = console [formatters] keys = generic [logger_root] level = WARN handlers = console [logger_testproj] level = WARN handlers = qualname = testproj [logger_sqlalchemy] level = WARN handlers = qualname = sqlalchemy.engine [logger_alembic] level = WARN handlers = qualname = alembic [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s Print Page Previous Next Advertisements ”;

Python Pyramid – Cookiecutter

Python Pyramid – Cookiecutter ”; Previous Next We have so far built the Pyramid application by manually performing the route configuration, adding the views and using the templates. Cookiecutter offers a convenient alternative to generate a Pyramid project structure. It is a command-line utility that uses certain predefined project templates. The project can then be fine-tuned to accommodate specific requirements that the user may have. The Python project created by Cookiecutter is a Python package. The default application logic can be further customized. The project structure so created is extremely extensible and is easy to distribute. The Cookiecutter utility is developed by Audrey Feldroy. It works on Python versions >=3.7. The project templates in Python, JavaScript, Ruby, CoffeeScript, languages or RST, Markdown, CSS, HTML scripts can be used to generate a project. Github hosts a number of pre-built project templates, any of which can be used. The project built from cookiecutter template is a cross-platform package. Cookiecutter project generation is completely automated and you don”t have to write any code for it. Once the cookiecutter command is invoked, it reads the template being used and prompts the user to choose appropriate values for the settings parameters. To begin with, install Cookiecutter with PIP installer. pip install cookiecutter To verify if Cookiecutter is correctly installed, run >>> import cookiecutter >>> cookiecutter.__version__ ”1.7.3” Print Page Previous Next Advertisements ”;

Python Pyramid – Deployment

Python Pyramid – Deployment ”; Previous Next The examples of Pyramid applications developed so far in this tutorial have been executed on the local machine. To make it accessible publicly, it must be deployed on a Production server capable of WSGI standards. Many WSGI compatible http servers are available for this purpose. For example − waitress paste.httpserver CherryPy uWSGI gevent mod_wsgi We have discussed how we can use Waitress server to host a Pyramid application. It can be served on ports 80 (HTTP) and 443 (HTTPS) of a machine having a public IP address. mod_wsgi Apache server is a popular open source HTTP server software, distributed by Apache Software Foundation. It powers most of the web servers across internet. The mod_wsgi (developed by Graham Dumpleton) is an Apache module that provides a WSGI interface for deploying Python based web applications on Apache. In this section, the step by step procedure to deploy a Pyramid application on the Apache server is explained. Here, we”ll use XAMPP, a popular open source Apache distribution. It can be downloaded from https://www.apachefriends.org/download.html. The mod_wsgi module is installed with PIP installer. Before installing, set the MOD_WSGI_APACHE_ROOTDIR environment variable to the directory in which Apache executable is located. C:Python310Scripts>set MOD_WSGI_APACHE_ROOTDIR=C:/xampp/apache C:Python310Scripts>pip install mod_wsgi Next, run the following command in the command terminal. C:Python310Scripts>mod_wsgi-express module-config LoadFile “C:/Python310/python310.dll” LoadModule wsgi_module “C:/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd” WSGIPythonHome “C:/Python310″ These are mod_wsgi module settings to be incorporated Apache”s configuration file. Open httpd.conf file of your XAMPP installation and copy the output of the above command line in it. Next, create a virtual host configuration for our application. Apache stores virtual host information in httpd-vhosts.conf file which is found in C:XAMPPApacheconfextra folder. Open the file and add following lines in it − <VirtualHost *> ServerName localhost:6543 WSGIScriptAlias / e:/pyramid-env/hello/production.ini <Directory e:/pyramid-env/hello> Order deny,allow Allow from all Require all granted </Directory> </VirtualHost> Here, it is assumed that a hello Pyramid project is built using the Cookiecutter utility. The PasteDeploy configuration file to be used in production environment is used here. This virtual host configuration needs to be incorporated in Apache”s httpd.conf file. This is done by adding following lines in it − # Virtual hosts Include conf/extra/httpd-vhosts.conf We now have to save the following code as pyramid.wsgi file that returns the Pyramid WSGI application object. from pyramid.paster import get_app, setup_logging ini_path = ”e:/pyramid-env/hello/production.ini” setup_logging(ini_path) application = get_app(ini_path, ”main”) After performing the above mentioned procedure, restart the XAMPP server and we should be able to run the Pyramid application on the Apache server. Deploy on Uvicorn Uvicorn is an ASGI compatible server (ASGI stands for Asynchronous Gateway Interface). Since Pyramid is a WSGI based web framework, we need to convert the WSGI application object to ASGI object, with the help of WsgiToAsgi() function defined in asgiref.wsgi module. from asgiref.wsgi import WsgiToAsgi from pyramid.config import Configurator from pyramid.response import Response def hello_world(request): return Response(“Hello”) with Configurator() as config: config.add_route(“hello”, “/”) config.add_view(hello_world, route_name=”hello”) wsgi_app = config.make_wsgi_app() app = WsgiToAsgi(wsgi_app) Save the above code as app.py. Install Uvicorn with pip utility. pip3 install uvicorn Run the Pyramid application in ASGI mode. uvicorn app:app Similarly, it can be served using daphne server. daphne app:app Print Page Previous Next Advertisements ”;

Python Pyramid – Package Structure

Python Pyramid – Package Structure ”; Previous Next The Cookiecutter utility automatically creates a package folder inside the parent project folder of the same name. The package folder consists of the following files and subfolders. __init__.py A folder needs __init__.py file for it to be treated as a Python package. The testproj package also has this file, which essentially declares the Pyramid WSGI application project for the development.ini to use it as the entry point. The application object is returned by the main() function. It configures the application registry by including the template library chosen at the time of running cookiecutter, including the routes module and adding the views to the configurator by scanning the existing package. Following Python code is auto generated as __init__.py file. from pyramid.config import Configurator def main(global_config, **settings): “”” This function returns a Pyramid WSGI application. “”” with Configurator(settings=settings) as config: config.include(”pyramid_jinja2”) config.include(”.routes”) config.include(”.models”) config.scan() return config.make_wsgi_app() routes.py The Cookiecutter utility automatically generates a Python script having a function called includeme(). It adds a static route and a home route pointing to ”/” URL pattern. def includeme(config): config.add_static_view(”static”, ”static”, cache_max_age=3600) config.add_route(”home”, ”/”) These routes are added to the application configuration by the main() function in __init__.py file explained above. Views Package The project package (in our case testproj package) contains this views subpackage – a folder containing a blank __init__.py, a Python module called default.py that contains definition a view function named my_view(). It sends the name of the project as a context to a pre-built template mytemplate.jinja2 from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.exc import SQLAlchemyError from .. import models @view_config(route_name=”home”, renderer=”testproj:templates/mytemplate.jinja2”) def my_view(request): try: query = request.dbsession.query(models.MyModel) one = query.filter(models.MyModel.name == ”one”).one() except SQLAlchemyError: return Response(db_err_msg, content_type=”text/plain”, status=500) return {”one”: one, ”project”: ”testproj”} db_err_msg = “”” Pyramid is having a problem using your SQL database. …. “”” The default.py scripts also imports definition of mymodel in models subpackage. This views package also defines a notfound view in notfound.py file. from pyramid.view import notfound_view_config @notfound_view_config(renderer=”testproj:templates/404.jinja2”) def notfound_view(request): request.response.status = 404 return {} Static Folder This folder under the testproj package folder contains Pyramid logo files and theme.CSS for the homepage. Templates Folder We know that the web templates need to be stored in templates folder. This subfolder contains jinja2 templates. Here we have a base template named as layout.jinja2 and it is inherited by mytemplate.jinja2 to be rendered by my_view() view function. {% extends “layout.jinja2″ %} {% block content %} <div class=”content”> <h1><span class=”font-semi-bold”>Pyramid</span> <span class=”smaller”>Starter project</span></h1> <p class=”lead”>Welcome to <span class=”font-normal”>{{project}}</span>, a Pyramid application generated by<br><span class=”font-normal”>Cookiecutter</span>.</p> </div> {% endblock content %} Models Package This subpackage under the tesptproj package folder holds mymodel.py that has the definition of SQLAlchemy model named as MyModel. from sqlalchemy import ( Column, Index, Integer, Text, ) from .meta import Base class MyModel(Base): __tablename__ = ”models” id = Column(Integer, primary_key=True) name = Column(Text) value = Column(Integer) Index(”my_index”, MyModel.name, unique=True, mysql_length=255) The meta.py declares an object of Declarative Base class in SQLAlchemy. from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.schema import MetaData NAMING_CONVENTION = { “ix”: “ix_%(column_0_label)s”, “uq”: “uq_%(table_name)s_%(column_0_name)s”, “ck”: “ck_%(table_name)s_%(constraint_name)s”, “fk”: “fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s”, “pk”: “pk_%(table_name)s” } metadata = MetaData(naming_convention=NAMING_CONVENTION) Base = declarative_base(metadata=metadata) Print Page Previous Next Advertisements ”;

Python Pyramid – Quick Guide

Python Pyramid – Quick Guide ”; Previous Next Python Pyramid – Overview Pyramid is an open source, WSGI compliant web framework written in Python. Initially the project named as Pylons, but later released under the new name Pyramid. Pyramid is a minimalistic web framework. It doesn”t come packaged with any templating library or doesn”t have support for any specific database packages. However, it can be integrated both with SQL databases via SQLAlchemy and with the Zope Object Database, as well as other NoSQL databases such as CouchDB. Pyramid can also be configured to work with templating libraries such as Mako, Jinja2 or Chameleon. Pyramid has been developed by Chris McDonough. The first version of Pyramid was released in January 2011. The latest version, Pyramid 2.0 has been released in March 2021. Comparison with Other Python Frameworks Pyramid web application framework is inspired by Zope and Django frameworks. As a result, it combines the best provisions of the two. Pyramid is largely based on repose.bfg framework. After it was merged with the Pylons project, the same was renamed as Pyramid in 2010. The ability to extend Pyramid application is borrowed from Zope library. Without modifying the application code, the application can be reused, modified or extended. The features such as declarative security layer and traversal of routes is inherited from Zope. As is the case of Pylons 1.0, Pyramid doesn”t enforce any policy. It also lets the user choose any database or templating system The URL dispatch approach is also inspired by Pylons. The concept of views is based on similar approach of Django. Extensive documentation is also a Django features adapted by Pyramid. Although the definition doesn”t fit exactly, Pyramid can be said to follow MVC (Model-View-Controller) approach. Python Pyramid – Environment Setup It is recommended that the Pyramid package be installed on a system having Python 3.6 or above version installed. Pyramid can be installed on Linux, MacOS as well as Windows platform. Simplest way of installing it is by using PIP installer, preferably under a Python virtual environment. pip3 install pyramid Although a Pyramid web application can be run using the built-in WSGI development server that is a part of the wsgiref module, it is not recommended for use in production environment. Hence, we also install Waitress, a production-quality pure-Python WSGI server (also a part of Pylons project). pip3 install waitress This will install Pyramid (ver 2.0), Waitress (ver 2.1.2) in addition to other dependencies from Pylon project such that WebOb, PasteDeploy, and others. To check what gets installed, run pip freeze command. pip3 freeze hupper==1.10.3 PasteDeploy==2.1.1 plaster==1.0 plaster-pastedeploy==0.7 pyramid==2.0 translationstring==1.4 venusian==3.0.0 waitress==2.1.2 WebOb==1.8.7 zope.deprecation==4.4.0 zope.interface==5.4.0 Python Pyramid – Hello World Example To check whether Pyramid along with its dependencies are properly installed, enter the following code and save it as hello.py, using any Python-aware editor. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def hello_world(request): return Response(”Hello World!”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() The Configurator object is required to define the URL route and bind a view function to it. The WSGI application object is obtained from this config object is an argument to the make_server() function along with the IP address and port of localhost. The server object enters a listening loop when serve_forever() method is called. Run this program from the command terminal as. Python hello.py Output The WSGI server starts running. Open the browser and enter http://loccalhost:6543/ in the address bar. When the request is accepted, the hello_world() view function gets executed. It returns the Hello world message. The Hello world message will be seen in the browser window. As mentioned earlier, the development server created by make_server() function in the wsgiref module is not suited for production environment. Instead, we shall use Waitress server. Modify the hello.py as per the following code − from pyramid.config import Configurator from pyramid.response import Response from waitress import serve def hello_world(request): return Response(”Hello World!”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() serve(app, host=”0.0.0.0”, port=6543) All other functionality is same, except we use serve() function of waitress module to start the WSGI server. On visiting the ”/” route in the browser after running the program, the Hello world message is displayed as before. Instead of a function, a callable class can also be used as a view. A callable class is the one which overrides the __call__() method. from pyramid.response import Response class MyView(object): def __init__(self, request): self.request = request def __call__(self): return Response(”hello world”) Python Pyramid – Application Configuration The Pyramid application object has an application registry that stores mappings of view functions to routes, and other application-specific component registrations. The Configurator class is used to build the application registry. The Configurator life cycle is managed by a context manager that returns an application object. with Configurator(settings=settings) as config: #configuration methods app = config.make_wsgi_app() The Configurator class defines the following important methods to customize the application − add_route() This method registers a route for URL dispatch. Following arguments are used − name − The first required positional argument must be a unique name for the route. The name is used to identify the route when registering views or generating URLs. pattern − The second required positional argument is a string representing the URL path optionally containing variable placeholders for parsing the variable data from the URL. The placeholders are surrounded by curly brackets. For example, “/students/{id}”. request_method − The value can be one of “GET”, “POST”, “HEAD”, “DELETE”, “PUT”. Requests only

Pyramid – Using SQLAlchemy

Python Pyramid – Using SQLAlchemy ”; Previous Next In this chapter, we shall learn how to use a relational database as a back-end with the Pyramid web application. Python can interact with almost every relational database using corresponding DB-API compatible connector modules or drivers. However, we shall use SQLAlchemy library as an interface between Python code and a database (we are going to use SQLite database as Python has in-built support for it). SQLAlchemy is a popular SQL toolkit and Object Relational Mapper. Object Relational Mapping is a programming technique for converting data between incompatible type systems in object-oriented programming languages. Usually, the type system used in an Object Oriented language like Python contains non-scalar types. However, data types in most of the database products such as Oracle, MySQL, etc., are of primitive types such as integers and strings. In an ORM system, each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an ORM takes care of these issues for you while you can focus on programming the logics of the system. In order to use SQLALchemy, we need to first install the library using PIP installer. pip install sqlalchemy SQLAlchemy is designed to operate with a DBAPI implementation built for a particular database. It uses dialect system to communicate with various types of DBAPI implementations and databases. All dialects require that an appropriate DBAPI driver is installed. The following are the dialects included − Firebird Microsoft SQL Server MySQL Oracle PostgreSQL SQLite Sybase Database Engine Since we are going to use SQLite database, we need to create a database engine for our database called test.db. Import create_engine() function from the sqlalchemy module. from sqlalchemy import create_engine from sqlalchemy.dialects.sqlite import * SQLALCHEMY_DATABASE_URL = “sqlite:///./test.db” engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args = {“check_same_thread”: False}) In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object. from sqlalchemy.orm import sessionmaker, Session session = sessionmaker(autocommit=False, autoflush=False, bind=engine) Next, we need a declarative base class that stores a catalog of classes and mapped tables in the Declarative system. from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() Model Class Students, a subclass of Base, is mapped to a students table in the database. Attributes in the Students class correspond to the data types of the columns in the target table. Note that the id attribute corresponds to the primary key in the book table. class Students(Base): __tablename__ = ”student” id = Column(Integer, primary_key=True, nullable=False) name = Column(String(63), unique=True) marks = Column(Integer) Base.metadata.create_all(bind=engine) The create_all() method creates the corresponding tables in the database. It can be confirmed by using a SQLite Visual tool such as SQLiteStudio. We shall now define view functions for performing CRUD operations (i.e. add, display, modify and delete rows) on the student table in the above database. Add a New Student Record First, we shall create a HTML form template for the user to enter student data and define a view that renders the template. Here is the myform.html template Example <html> <body> <form method=”POST” action=”http://localhost:6543/add”> <p>Student Id: <input type=”text” name=”id”/> </p> <p>student Name: <input type=”text” name=”name”/> </p> <p>Percentage: <input type=”text” name=”percent”/> </p> <p><input type=”submit” value=”Submit”> </p> </body> </html> In the Pyramid application code, define the index() view function to render the above form. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config(route_name=”index”, renderer=”templates/myform.html”) def index(request): return {} In the application configuration, register the route with the “/new” pattern for this view as − if __name__ == ”__main__”: with Configurator() as config: config.include(”pyramid_jinja2”) config.add_jinja2_renderer(“.html”) config.add_route(”index”, ”/new”) config.scan() app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() As the HTML form in the above template is submitted to /add URL with POST action, we need to map this URL to add route and register add() view that parses the form data into an object of Students class. This object is added to the database session and the operation is finalized by calling its commit() method. @view_config(route_name=”add”, request_method=”POST”) def add(request): id=request.POST[”id”] name=request.POST[”name”] percent=int(request.POST[”percent”]) student=Students(id=id, name=name, percent=percent) session.add(student) session.commit() return HTTPFound(location=”http://localhost:6543/”) Make sure that the add route is added in the configuration, mapped to /add URL pattern. config.add_route(”add”,”/add”) Output If we start the server and open http://localhost:6543/new in the browser, the Entry form will be displayed as follows − Fill the form and press the “submit” button. The add() view will be called and a new record will be added in the students table. Repeat the process a couple of times to add a few records. Here is a sample data − Show List of All Records All the objects of the Students model (corresponding to row in students table) are obtained by querying the model. rows = session.query(Students).all() Each row is converted into a dict object, all of them are appended to a list of dict objects, and returned as a context to the list.html template to be displayed in the form of HTML template. The process is performed by the showall() view function, associated with list route. @view_config(route_name=”list”, renderer=”templates/marklist.html”) def showall(request): rows = session.query(Students).all() students=[] for row in rows: students.append({“id”:row.id, “name”:row.name, “percent”:row.percent}) return{”students”:students} Example The marklist.html template renders the Students list as a HTML table. Its HTML/jinja2 script is as follows − <html> <body> <table border=1> <thead> <tr> <th>Student ID</th> <th>Student Name</th> <th>percentage</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {% for Student in students %} <tr> <td>{{ Student.id }}</td> <td>{{ Student.name }}</td> <td>{{ Student.percent }}</td>

Python Pyramid – Sessions

Python Pyramid – Sessions ”; Previous Next A session is a time interval between client logs into a server and it logs out of it. Session object is also a dictionary object containing key-value pairs of session variables and associated values. In Pyramid, it is available as an attribute of request object. In order to handle session mechanism, the Pyramid Application object must be configured with a session factory that returns the session object. Pyramid core provides a basic session factory, which uses cookies to store session information. Default Session Factory The pyramid.session module defines SignedCookieSessionFactory class. Its object needs a secret key for digitally signing the session cookie information. from pyramid.session import SignedCookieSessionFactory my_session_factory = SignedCookieSessionFactory(”abcQWE123!@#”) The set_session_factory() method of the Configurator class uses this factory object to set up the session. config.set_session_factory(my_session_factory) Once this is done, the session object is now available for implementation as request.session attribute. To add a session variable, use − request.session[”user”] = ”Admin” To retrieve a session variable, use − user=request.session[”user”] To remove a session variable, use the pop() method. request.session.pop(”user”) Session Example Described below is the usage of session variable in a Pyramid application. First, the login route (associated with login() view function) brings up a login form on the browser. @view_config(route_name=”login”) def login(request): html=””” <html> <body> <form action=”/add”> Enter User name : <input type=”text” name=”user”> <input type=”submit” value=”submit”> </form> </body> </html> “”” return Response(html) The add() function reads the ”user” form attribute and uses its value to add a session variable. @view_config(route_name=”addsession”) def add(request): request.session[”user”]=request.params[”user”] return Response(“<h2>Session object added.</h2><br><h3><a href=”/read”>click here</a></h3>”) The read() view reads back the session variable data and displays a welcome message. @view_config(route_name=”readsession”) def read(request): user=request.session[”user”] response=”<h2>Welcome {} </h2>”.format(user)+”<br><h3><a href=”/logout”>Logout</a></h3>” return Response(response) These views along with the session factory are added in the application configuration. config.set_session_factory(my_session_factory) config.add_route(”login”,”/”) config.add_route(”logout”,”/logout”) config.add_route(”addsession”, ”/add”) config.add_route(”readsession”, ”/read”) config.scan(”session”) Example The complete code is given below − from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config from pyramid.session import SignedCookieSessionFactory my_session_factory = SignedCookieSessionFactory(”abcQWE123!@#”) @view_config(route_name=”login”) def login(request): html=””” <html> <body> <form action=”/add”> Enter User name : <input type=”text” name=”user”> <input type=”submit” value=”submit”> </form> </body> </html> “”” return Response(html) @view_config(route_name=”addsession”) def add(request): request.session[”user”]=request.params[”user”] return Response(“<h2>Session object added.</h2><br><h3><a href=”/read”>click here</a></h3>”) @view_config(route_name=”readsession”) def read(request): user=request.session[”user”] response=”<h2>Welcome {} </h2>”.format(user)+”<br><h3><a href=”/logout”>Logout</a>>/<h3>” return Response(response) @view_config(route_name=”logout”) def logout(request): request.session.pop(”user”) response=”<h2>You have been logged out </h2><br><h3><a href=”/”>Login</a></h3>” return Response(response) if __name__ == ”__main__”: with Configurator() as config: config.set_session_factory(my_session_factory) config.add_route(”login”,”/”) config.add_route(”logout”,”/logout”) config.add_route(”addsession”, ”/add”) config.add_route(”readsession”, ”/read”) config.scan(”session”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Save this script as main.py in a subfolder (called ”session”) within the Pyramid virtual environment folder. Note that this subfolder must have an empty __init__.py file for it to be treated as a package. Output Run main.py and enter http://localhost:6543/ to open up the login form in the browser. Enter the user name and press the “submit” button. The given name is saved as a ”user” session variable. The ”click here” link reads back the session variable and displays welcome message. The logout link pops the session variable and takes the browser back to the login page. Print Page Previous Next Advertisements ”;