<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Davit Tovmasyan on Medium]]></title>
        <description><![CDATA[Stories by Davit Tovmasyan on Medium]]></description>
        <link>https://medium.com/@davittovmasyan?source=rss-d6b25f39386------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YsTBjIzuJlrkvVukP0bclA.jpeg</url>
            <title>Stories by Davit Tovmasyan on Medium</title>
            <link>https://medium.com/@davittovmasyan?source=rss-d6b25f39386------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:57:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davittovmasyan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to make your code fast and asynchronous with Python and Sanic]]></title>
            <link>https://medium.com/@davittovmasyan/goin-fast-and-asynchronous-with-python-and-sanic-387d722f3668?source=rss-d6b25f39386------2</link>
            <guid isPermaLink="false">https://medium.com/p/387d722f3668</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[sanic]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Davit Tovmasyan]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 08:57:06 GMT</pubDate>
            <atom:updated>2019-05-17T10:51:49.887Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everybody. In this article, I’ll talk about building simple asynchronous projects with the Sanic framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vJxAS5gEDCUgnTntr5eSRg.jpeg" /><figcaption>Goin’ Fast</figcaption></figure><h3>Introduction</h3><p><a href="https://sanicframework.org/">Sanic</a><strong> </strong>is a very flask-like open-source Python web server and web framework with more than <a href="https://github.com/huge-success/sanic">10K stars</a> that’s written to go fast. It allows the usage of async/await syntax added in Python 3.5 (<a href="https://docs.python.org/3/library/asyncio-task.html">read more</a>), which makes your code <a href="https://medium.com/vaidikkapoor/understanding-non-blocking-i-o-with-python-part-1-ec31a2e2db9b">non-blocking</a> and speedy.</p><p>Sanic has pretty good <a href="https://sanic.readthedocs.io/en/latest/">documentation</a> and it’s maintained by the community, for the community.</p><blockquote>The goal of the project is to provide a simple way to get a highly performant HTTP server up and running that is easy to build, to expand, and ultimately to scale.</blockquote><h3>Requirements</h3><p>Before we start, let’s install some packages and make sure that we have everything ready for the development of this project.</p><p><em>Note: Source code is available in my </em><a href="https://github.com/davitovmasyan/sanic-project"><em>github.com</em></a><em> repository. For each step, there is a corresponding commit.</em></p><h4>Prerequisites:</h4><ul><li>Python3.6+</li><li><a href="https://github.com/pypa/pipenv">pipenv</a> (you can use any other package installer)</li><li><a href="https://www.postgresql.org/">PostgreSQL</a><strong> </strong>(for database, can also be MySQL or SQLite)</li></ul><h4>Packages:</h4><ul><li><a href="https://pypi.org/project/secure/">secure</a> is a lightweight package that adds optional security headers and cookie attributes for Python web frameworks.</li><li><a href="https://pypi.org/project/environs/">environs</a> is a Python library for parsing environment variables. It allows you to store configuration separate from your code, as per <a href="https://12factor.net/config">The Twelve-Factor App</a> methodology.</li><li><a href="https://github.com/jamesstidard/sanic-envconfig">sanic-envconfig</a> is an extension that helps you bring command line &amp; environment variables into your Sanic config.</li><li><a href="https://pypi.org/project/databases/">databases</a> is a Python package that allows you to make queries using the powerful <a href="https://docs.sqlalchemy.org/en/latest/core/">SQLAlchemy Core</a> expression language and provides support for PostgreSQL, MySQL, and SQLite.</li></ul><p>Let’s create an empty directory and initialize an empty Pipfile there.</p><pre>pipenv  -- python python3.6</pre><p>Install all necessary packages using <strong>pipenv</strong> commands below.</p><pre>pipenv install sanic secure environs sanic-envconfig</pre><p>For the database:</p><pre>pipenv install databases[postgresql]</pre><p>Choices are<em> </em><strong>postgresql, mysql, sqlite.</strong></p><h3>Structure</h3><p>Now let’s create some files and folders where we will write our actual code.</p><pre>├── .env<br>├── Pipfile<br>├── Pipfile.lock<br>├── setup.py<br>└── project<br>    ├── __init__.py<br>    ├── __main__.py<br>    ├── main.py<br>    ├── middlewares.py<br>    ├── routes.py<br>    ├── settings.py<br>    └── tables.py</pre><p>We will use the setup.py file to make the project folder available as a package in our code.</p><pre>from setuptools import setup<br><br>setup(<br>    name=&#39;project&#39;,<br>)</pre><p><em>Installing…</em></p><pre>pipenv install -e .</pre><p>In the .env file, we’ll store some global variables like the database connection URL.</p><p>__main__.py is created for making our project package executable from the command-line.</p><pre>pipenv run python -m project</pre><h3>Initialization</h3><p>Let’s do our first call in <strong>__main__.py</strong> file.</p><pre>from project.main import init<br><br>init()</pre><p>This is the beginning of our application. Now we need to create the init function inside of <strong>main.py</strong> file.</p><pre>from sanic import Sanic<br><br>app = Sanic(__name__)<br><br>def init():<br>    app.run(host=&#39;0.0.0.0&#39;, port=8000, debug=True)</pre><p>Simply creating the app from the <em>Sanic</em> class we can run it specifying <strong>host</strong>, <strong>port </strong>and optional <strong>debug </strong>keyword argument.</p><p><em>Running…</em></p><pre>pipenv run python -m project</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*GVVZ3nvjECTiggzNuNkE9w.png" /><figcaption>Sanic console output</figcaption></figure><p>This is how a successful output should look in your Sanic app. If you open <a href="http://0.0.0.0:8000/">http://0.0.0.0:8000</a> on your browser you’ll see</p><blockquote>Error: Requested URL / not found</blockquote><p>We haven’t created any <strong>routes </strong>yet, so it’s fine for now. We will add some routes below.</p><h3>Settings</h3><p>Now we can modify the environment and settings. We need to add some variables in the <strong>.env</strong> file, read them, and pass to Sanic app config.</p><p><strong><em>.env </em></strong><em>file.</em></p><pre>DEBUG=True<br>HOST=0.0.0.0<br>POST=8000</pre><p><em>Configuration…</em></p><pre>from sanic import Sanic</pre><pre><strong>from environs import Env</strong><br><strong>from project.settings import Settings</strong></pre><pre>app = Sanic(__name__)</pre><pre>def init():<br>    <strong>env = Env()<br>    env.read_env()<br>    <br>    app.config.from_object(Settings)</strong><br><strong>    </strong>app.run(<br>        host=<strong>app.config.HOST</strong>, <br>        port=<strong>app.config.PORT</strong>, <br>        debug=<strong>app.config.DEBUG</strong>,<br>        <strong>auto_reload=app.config.DEBUG,</strong><strong>    <br>    </strong>)</pre><p><strong><em>settings.py </em></strong><em>file.</em></p><pre>from sanic_envconfig import EnvConfig<br><br><br>class Settings(EnvConfig):<br>    DEBUG: bool = True<br>    HOST: str = &#39;0.0.0.0&#39;<br>    PORT: int = 8000</pre><p>Please note that I’ve added an optional <strong>auto_reload </strong>argument which will activate or deactivate the Automatic Reloader.</p><h3>Database</h3><p>Now it’s time to set up a database.</p><p>One little note about the <strong>databases </strong>package before we go ahead:</p><blockquote><strong>databases </strong>package uses <a href="https://github.com/MagicStack/asyncpg">asyncpg</a><strong> </strong>which is an asynchronous interface library for PostgreSQL. It’s pretty fast. See results below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*-TQPe-Es0qUTBi737ooNIg.png" /></figure><p>We will use two of Sanic’s <a href="https://sanic.readthedocs.io/en/latest/sanic/middleware.html#listeners">listeners</a> where we will specify database connect and disconnect operations. Here are the listeners that we are going to use:</p><ul><li><strong>after_server_start</strong></li><li><strong>after_server_stop</strong></li></ul><p><strong><em>main.py</em></strong><em> file.</em></p><pre>from sanic import Sanic</pre><pre><strong>from databases import Database</strong></pre><pre>from environs import Env<br>from project.settings import Settings</pre><pre>app = Sanic(__name__)</pre><pre><strong>def setup_database():<br>    app.db = Database(app.config.DB_URL)<br><br>    @app.listener(&#39;after_server_start&#39;)<br>    async def connect_to_db(*args, **kwargs):<br>        await app.db.connect()<br><br>    @app.listener(&#39;after_server_stop&#39;)<br>    async def disconnect_from_db(*args, **kwargs):<br>        await app.db.disconnect()</strong></pre><pre>def init():<br>    env = Env()<br>    env.read_env()<br>    <br>    app.config.from_object(Settings)</pre><pre>    <strong>setup_database()</strong></pre><pre><strong>    </strong>app.run(<br>        host=app.config.HOST, <br>        port=app.config.PORT, <br>        debug=app.config.DEBUG,<br>        auto_reload=app.config.DEBUG,    <br>    )</pre><p>Once more thing. We need to specify <strong>DB_URL </strong>in project settings and environment.</p><p><strong><em>.env </em></strong><em>file.</em></p><pre>DEBUG=True<br>HOST=0.0.0.0<br>POST=8000<br><strong>DB_URL=postgresql://postgres:postgres@localhost/postgres</strong></pre><p><em>And </em><strong><em>settings.py</em></strong><em> file.</em></p><pre>from sanic_envconfig import EnvConfig<br><br><br>class Settings(EnvConfig):<br>    DEBUG: bool = True<br>    HOST: str = &#39;0.0.0.0&#39;<br>    PORT: int = 8000<br>    <strong>DB_URL: str = &#39;&#39;</strong></pre><p>Make sure that <strong>DB_URL</strong> is correct and your database is running. Now you can access to the database using <strong>app.db. </strong>See more detailed information in the next section.</p><h3>Tables</h3><p>Now we have a connection to our database and we can try to do some SQL queries.</p><p>Let’s declare a table in <strong>tables.py</strong> file using SQLAlchemy.</p><pre>import sqlalchemy<br><br><br>metadata = sqlalchemy.MetaData()<br><br>books = sqlalchemy.Table(<br>    &#39;books&#39;,<br>    metadata,<br>    sqlalchemy.Column(&#39;id&#39;, sqlalchemy.Integer, primary_key=True),<br>    sqlalchemy.Column(&#39;title&#39;, sqlalchemy.String(length=100)),<br>    sqlalchemy.Column(&#39;author&#39;, sqlalchemy.String(length=60)),<br>)</pre><p>Here I assume that you already have a <strong>migrated</strong> database with a <strong>books</strong> table in it. For creating database migrations, I recommend that you use <a href="https://alembic.sqlalchemy.org/">Alembic</a> which is a lightweight and easy-to-use tool that you can use with the SQLAlchemy Database Toolkit for Python.</p><p>Now we can use any <a href="https://docs.sqlalchemy.org/en/latest/core/">SQLAlchemy core</a> queries. Check out some examples below.</p><pre># Executing many<br><strong>query = books.insert()<br>values = [<br>    {&quot;title&quot;: &quot;No Highway&quot;, &quot;author&quot;: &quot;Nevil Shute&quot;},<br>    {&quot;title&quot;: &quot;The Daffodil&quot;, &quot;author&quot;: &quot;SkyH. E. Bates&quot;},<br>]</strong><br><strong>await app.db.execute_many(query, values)</strong><br><br># Fetching multiple rows<br><strong>query = books.select()</strong><br><strong>rows = await app.db.fetch_all(query)<br></strong><br># Fetch single row<br><strong>query = books.select()</strong><br><strong>row = await app.db.fetch_one(query)</strong></pre><h3>Routes</h3><p>Now we need to set up routes. Let’s go to <strong>routes.py </strong>and add a new route for books.</p><pre>from sanic.response import json</pre><pre>from project.tables import books</pre><pre><br>def setup_routes(app):<br>    @app.route(&quot;/books&quot;)<br>    async def book_list(request):<br>        query = books.select()<br>        rows = await request.app.db.fetch_all(query)<br>        return json({<br>            &#39;books&#39;: [{row[&#39;title&#39;]: row[&#39;author&#39;]} for row in rows]<br>        })</pre><p>Of course we need to call <strong>setup_routes </strong>in <strong>init </strong>to make it work.</p><pre><strong>from project.routes import setup_routes</strong></pre><pre>app = Sanic(__name__)</pre><pre>def init():<br>    ...<br>    app.config.from_object(Settings)<br>    setup_database()<strong><br>    setup_routes(app)<br>    </strong>...</pre><p><em>Requesting…</em></p><pre>$ curl localhost:8000/books<br><em>{&quot;books&quot;:[{&quot;No Highway&quot;:&quot;Nevil Shute&quot;},{&quot;The Daffodil&quot;:&quot;SkyH. E. Bates&quot;}]}</em></pre><h3>Middlewares</h3><p>What about checking the <strong>response</strong> headers and seeing what we can add or fix there?</p><pre>$ curl -I localhost:8000<br>Connection: keep-alive<br>Keep-Alive: 5<br>Content-Length: 32<br>Content-Type: text/plain; charset=utf-8</pre><p>As you can see we need some security improvements. There are some missing headers such as<strong> X-XSS-Protection, Strict-Transport-Security</strong>…<strong> </strong>so let’s take care of them using a combination of <a href="https://sanic.readthedocs.io/en/latest/sanic/middleware.html#middleware">middlewares</a> and <strong>secure</strong> packages.</p><p><strong><em>middlewares.py</em></strong><em> file.</em></p><pre>from secure import SecureHeaders<br><br>secure_headers = SecureHeaders()<br><br>def setup_middlewares(app):<br>    @app.middleware(&#39;response&#39;)<br>    async def set_secure_headers(request, response):<br>        secure_headers.sanic(response)</pre><p><em>Setting up middlewares in </em><strong><em>main.py</em></strong><em> file.</em></p><pre><strong>from project.middlewares import setup_middlewares</strong></pre><pre>app = Sanic(__name__)</pre><pre>def init():<br>    ...<br>    app.config.from_object(Settings)<br>    setup_database()<br>    setup_routes(app)<br><strong>    setup_middlewares(app)<br>    </strong>...</pre><p><em>The result is:</em></p><pre>$ curl -I localhost:8000/books<br>Connection: keep-alive<br>Keep-Alive: 5<br><strong>Strict-Transport-Security: max-age=63072000; includeSubdomains<br>X-Frame-Options: SAMEORIGIN<br>X-XSS-Protection: 1; mode=block<br>X-Content-Type-Options: nosniff<br>Referrer-Policy: no-referrer, strict-origin-when-cross-origin<br>Pragma: no-cache<br>Expires: 0<br>Cache-control: no-cache, no-store, must-revalidate, max-age=0</strong><br>Content-Length: 32<br>Content-Type: text/plain; charset=utf-8</pre><p>As I promised at the beginning, there is a <a href="https://github.com/davitovmasyan/sanic-project">github repository</a> for each <a href="https://github.com/davitovmasyan/sanic-project/tags">section</a> in this article. Hope this small tutorial helped you to get started with Sanic. There are still many unexplored features in the Sanic framework that you can find and check out in the <a href="https://sanic.readthedocs.io/en/latest/">documentation</a>.</p><p><a href="https://github.com/davitovmasyan/sanic-project">davitovmasyan/sanic-project</a></p><p>If you have thoughts on this, be sure to leave a comment.</p><p>If you found this article helpful, give me some claps 👏</p><p>Thanks for reading. Go Fast with Sanic and good luck!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=387d722f3668" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>