<?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[Django Framework — Real World Projects - Medium]]></title>
        <description><![CDATA[a publication on practical projects with the django framework - Medium]]></description>
        <link>https://medium.com/django-framework-real-world-projects?source=rss----86ab17bb8091---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Django Framework — Real World Projects - Medium</title>
            <link>https://medium.com/django-framework-real-world-projects?source=rss----86ab17bb8091---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:15:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/django-framework-real-world-projects" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Real Face of Python — Context Sensitivity]]></title>
            <link>https://medium.com/django-framework-real-world-projects/the-real-face-of-python-context-sensitivity-8acfd514b413?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/8acfd514b413</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 03:18:04 GMT</pubDate>
            <atom:updated>2020-10-05T03:30:22.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Real Face of Python — Context Sensitivity</h3><p><strong><em>updated</em></strong> for <strong><em>python 3.8.3</em></strong></p><p><em>Fortes fortuna adiuvat, Fortuna Eruditis Favet.</em></p><p><em>To completely understand the Python/C API, build custom types.</em></p><p><em>Working with the Python/C API gets you close to understanding language implementation.</em></p><h3>Introduction</h3><p>Modern programming languages are algebraic languages. The concept of an <strong><em>identifier</em></strong> is central. An <strong><em>identifier</em></strong> is used to denote mathematical primitives like variables, types, functions etc.</p><p>Each <strong><em>identifier</em></strong> introduced (either through a <strong><em>declaration</em></strong> or direct <strong><em>definition </em></strong>for languages that doesn’t support <strong><em>explicit declarations</em></strong>) is associated with an <strong><em>object</em></strong> of the computing process that has <strong><em>certain properties</em></strong>. For example the <strong><em>class of the object</em></strong> (either a variable, user-defined function, built-in function, type etc) which the identifier is associated with. In language implementation, a <strong><em>symbol table</em></strong> is used to record this <strong><em>properties</em></strong> that <strong><em>decide</em></strong> how the identifier can be used when it is encountered.</p><p>This <strong><em>symbol table</em></strong> can be as simple as a<strong><em> linked structure</em></strong> of <strong><em>record types</em></strong> contain <strong><em>fields</em></strong> like the <strong><em>name of the object</em></strong>, its <strong><em>class</em></strong>, <strong><em>reference count</em></strong>, <strong><em>pointer to its type</em></strong> etc.</p><h3>Enter Python</h3><p>In python, identifiers are associated with an object, <strong><em>PyObject* </em></strong>. Which at a basic level contains a <strong><em>reference count</em></strong> and a pointer to the object’s<strong><em> type object</em></strong>, <strong><em>PyTypeObject</em></strong>.</p><p>To prevent our programs from leaking memory, the reference count is employed. It counts the places the object is referenced. When the count reaches zero, the object is deallocated.</p><p>A custom type might look like this,</p><pre>static PyTypeObject Custom_Type = {<br>  PyVarObject_HEAD_INIT(NULL, 0)<br>  &quot;custom.Custom&quot;,               /* tp_name */<br>  sizeof(CustomObject),          /* tp_basicsize */<br>  0,                             /* tp_itemsize */<br>  (destructor)custom_dealloc,    /* tp_dealloc */<br>  0,                             /* tp_vectorcall_offset */<br>  0,                             /* tp_getattr */<br>  0,                             /* tp_setattr */<br>  0,                             /* tp_as_async */<br>  (reprfunc)custom_repr,         /* tp_repr */<br>  0,                             /* tp_as_number */<br>  0,                             /* tp_as_sequence */<br>  0,                             /* tp_as_mapping */<br>  0,                             /* tp_hash */<br>  0,                             /* tp_call */<br>  0,                             /* tp_str */<br>  0,                             /* tp_getattro */<br>  0,                             /* tp_setattro */<br>  0,                             /* tp_as_buffer */<br>  0,                             /* tp_flags */<br>  0,                             /* tp_doc */<br>  0,                             /* tp_traverse */<br>  0,                             /* tp_clear */<br>  0,                             /* tp_richcompare */<br>  0,                             /* tp_weaklistoffset */<br>  0,                             /* tp_iter */<br>  0,                             /* tp_iternext */<br>  0,                             /* tp_methods */<br>  0,                             /* tp_members */<br>  0,                             /* tp_getset */<br>  0,                             /* tp_base */<br>  0,                             /* tp_dict */<br>  0,                             /* tp_descr_get */<br>  0,                             /* tp_dictoffset */<br>  0,                             /* tp_init */<br>  0,                             /* tp_alloc */<br>  0,                             /* tp_alloc */<br>  custom_new,                    /* tp_new */<br>};</pre><p>As can be seen from the sample type above, the type object determines the C functions that are called by the interpreter when different operations are carried out on its representing identifier.</p><h3>Backtracking A bit</h3><p>We are dealing with a computing device which has a memory, processor etc. and an operating system that manages whatever resources the computing device provides.</p><p>If we define a variable, a storage location has to be provided for it. Hence for every object you create in python, space must be <strong><em>allocated </em></strong>for it. All python objects are allocated on the<strong><em> heap</em></strong>.</p><p>Our computing device has limited storage, hence if we are not using an <strong><em>allocated space</em></strong>, it should be <strong><em>deallocated </em></strong>and <strong><em>freed</em></strong> for another computing process to use it. Hence we must provide a strategy to make sure we don’t retain storage we are not using.</p><h3>Back to Python</h3><p>Python provides the <strong><em>__new__</em></strong>, <strong><em>__bases__</em></strong>,<strong><em> __getattr__</em></strong>, <strong><em>__call__, __init__ </em></strong>etc methods for types. As can be seen from the above type, provision is provided for you to create custom functions to target them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8acfd514b413" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/the-real-face-of-python-context-sensitivity-8acfd514b413">The Real Face of Python — Context Sensitivity</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Real Face of Python — An Introduction]]></title>
            <link>https://medium.com/django-framework-real-world-projects/the-real-face-of-python-an-introduction-d4a7e2c515c0?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/d4a7e2c515c0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Fri, 02 Oct 2020 03:28:09 GMT</pubDate>
            <atom:updated>2020-11-16T11:34:06.917Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Real Face of Python — An Introduction</h3><p><strong><em>updated</em></strong> for <strong><em>Python 3.8.3</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*mQkJOLceWkY-HO0E7WmSyw.jpeg" /><figcaption>by Lukas Blazek — Unsplash</figcaption></figure><p><em>For the sake of performance and reliability, solve interpreted problems in interpreted languages and compiled problems in compiled languages.</em></p><p><em>Python gives you the power of three languages: an interpreted language Python and two compiled languages C and C++.</em></p><p><em>When I talk about Python, I mean CPython</em>.</p><h3>Introduction</h3><p>It is very difficult (if not impossible) for an interpreted language to beat the execution speed of a compiled language.</p><p>One of the selling points of Python is the speed (development speed) at which ideas can be bootstrapped using it. But as web apps are becoming very ambitious in providing solutions with god-like speed, interpreted languages are put on trial. Here enters the Python/C API.</p><p>CPython gives you the speed of compiled languages through the Python/C API. With this, performance (if needed, after profiling) can be added based on stepwise refinement of your original solution without altering your source code. This is explained below.</p><p>Consider a module <strong><em>first.py</em></strong> that defines a type <strong><em>A</em></strong> that is a critical component of a particular project as shown below:</p><pre># module first.py</pre><pre><br># A might define additional attributes and methods<br>class A(dict):<br>  pass</pre><p>A python developer reasoning in python, uses type <strong><em>A</em></strong> to solve the problem it was intended for, it worked, everybody is happy.</p><p>But then your project starts suffering from performance problem, and after profiling you found out that <strong><em>A</em></strong> is the culprit. You can solve the performance problem by stepwise refinement of module <strong><em>first.py</em></strong> with a single import without altering <strong><em>A</em></strong> as shown below.</p><pre># new first.py</pre><pre># A might define additional attributes and methods<br>class A(dict):<br>  pass</pre><pre>try:<br>  from _utils import _A as A<br>except ImportError:<br>  pass</pre><p>Where <strong><em>_A</em></strong> is defined in an extension module <strong><em>_utilsmodule.c</em></strong> by a python developer reasoning in the C programming language.</p><h3>Without Further Ado</h3><p>Everything is an object in python. The CPython implementation sees this objects as variables of the type <strong><em>PyObject*</em></strong>. Each of this objects have a <strong><em>type</em></strong> and a <strong><em>reference count</em></strong>.</p><p>Thus we can define <strong><em>_A</em></strong> in <strong><em>_utilsmodule.c</em></strong> as shown below.</p><pre>#define PY_SSIZE_T_CLEAN<br>#include &lt;Python.h&gt;</pre><pre>/* Our object */<br>typedef struct {<br>  PyDictObject dict;<br>} AObject;</pre><pre>/* Our Type */<br>static PyTypeObject AType = {<br>  PyVarObject_HEAD_INIT(NULL, 0)<br>  .tp_name = &quot;_utils._A&quot;,<br>  .tp_doc = &quot;_A objects&quot;,<br>  .tp_basicsize = sizeof(AObject),<br>  .tp_itemsize = 0,<br>  .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,<br>};</pre><pre>/* Our Module */<br>static PyModuleDef _amodule = {<br>  PyModuleDef_HEAD_INIT,<br>  .m_name = &quot;_utils&quot;,<br>  .m_doc = &quot;_utils provides efficient data strutures and algorithms&quot;,<br>  .m_size = -1,<br>};</pre><pre>/* Initialize our module */<br>PyMODINIT_FUNC<br>PyInit__utils(void)<br>{<br>  PyObject *m;</pre><pre>  AType.tp_base = &amp;PyDict_Type;<br>  if (PyType_Ready(&amp;AType) &lt; 0)<br>    return NULL;</pre><pre>  m = PyModule_Create(&amp;_amodule);<br>  if (m == NULL)<br>    return NULL;</pre><pre>  Py_INCREF(&amp;AType);<br>  if (PyModule_AddObject(m, &quot;_A&quot;, (PyObject *)&amp;AType)) {<br>    Py_DECREF(&amp;AType);<br>    Py_DECREF(m);<br>    return NULL;<br>  }<br>  return m;<br>}</pre><p>To build and install we first create a <em>setup.py</em> file as shown below.</p><pre># setup.py<br>from distutils.core import Extension, setup</pre><pre>setup(name=&quot;UtilsPackage&quot;,<br>  version=&quot;1.0.0&quot;,<br>  author=&quot;Nwafor Chukwunonso&quot;,<br>  ext_modules = [Extension(name=&quot;_utils&quot;, sources=[&quot;_utilsmodule.c&quot;])]<br>)</pre><p>We can build using the command</p><pre>python setup.py build</pre><p>and install using the command</p><pre>python setup.py install</pre><h3>Showing Use Case</h3><p>We can use type <strong><em>_A</em></strong> as you would the default <strong><em>dict</em></strong> type. as shown below.</p><pre>&gt;&gt;&gt; from _utils import _A as A<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; A<br>&lt;class &#39;_utils._A&#39;&gt;<br>&gt;&gt;&gt; A.__bases__<br>(&lt;class &#39;dict&#39;&gt;,)<br>&gt;&gt;&gt; <br>&gt;&gt;&gt; type(A)<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(A())<br>&lt;class &#39;_utils._A&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; a = A({&quot;obi&quot;: &quot;chidi&quot;, &quot;nwafor&quot;: &quot;chukwunonso&quot;})<br>&gt;&gt;&gt; a<br>{&#39;obi&#39;: &#39;chidi&#39;, &#39;nwafor&#39;: &#39;chukwunonso&#39;}<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; a[&quot;nwafor&quot;]<br>&#39;chukwunonso&#39;<br>&gt;&gt;&gt;</pre><h3>Use Case from first.py</h3><p>We originally defined the extension module to be callable from <strong><em>first.py</em></strong>. So let us test it.</p><pre>&gt;&gt;&gt; from first import A<br>&gt;&gt;&gt; A<br>&lt;class &#39;_utils._A&#39;&gt;<br>&gt;&gt;&gt;</pre><p>Well for starters it worked. Our type <strong><em>_A</em></strong> from module <strong><em>_utils</em></strong> was called. But we noticed something else, the class of <em>A</em> is not <strong><em>&lt;class ‘first.A’&gt;</em></strong> but <strong><em>&lt;class ‘_utils._A’&gt;</em></strong>, this can result in confusion depending on the use case of <strong><em>_utils</em></strong>.</p><ol><li>We can change the<em> </em><strong><em>tp_name</em></strong> of <strong><em>AType</em></strong> in <strong><em>_utilsmodule.c</em></strong> to <strong><em>“first.A”</em></strong> from <strong><em>“_utils._A” </em></strong>to reflect that we are calling <strong><em>_A</em></strong> from <strong><em>first.py</em></strong>. With that, If we build and install we now have:</li></ol><pre>&gt;&gt;&gt; from first import A<br>&gt;&gt;&gt; A<br>&lt;class &#39;first.A&#39;&gt;<br>&gt;&gt;&gt; A.__module__<br>&#39;first&#39;<br>&gt;&gt;&gt; A()<br>{}<br>&gt;&gt;&gt;</pre><p>Exactly as we wanted. However this has radically decoupled <strong><em>_A</em></strong> from <strong><em>_utils </em></strong>based on the change of<strong><em> tp_name</em></strong>. If we want to use <strong><em>_A</em></strong> from <strong><em>_utils</em></strong> without going through <strong><em>first.py</em></strong>, we also have the same problem of it showing <strong><em>&lt;class ‘first.A’&gt;</em></strong> instead of <strong><em>&lt;class ‘_utils._A’&gt; </em></strong>as shown below.</p><pre>&gt;&gt;&gt; from _utils import _A<br>&gt;&gt;&gt; _A<br>&lt;class &#39;first.A&#39;&gt;<br>&gt;&gt;&gt;</pre><p>This two points should be considered when you create your extension modules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a7e2c515c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/the-real-face-of-python-an-introduction-d4a7e2c515c0">The Real Face of Python — An Introduction</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[urls — An Introduction]]></title>
            <link>https://medium.com/django-framework-real-world-projects/urls-an-introduction-373b8558a1b8?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/373b8558a1b8</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[url]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 19:58:50 GMT</pubDate>
            <atom:updated>2020-04-21T08:19:39.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>urls — An Introduction</h3><p><strong>updated</strong> for <strong>python</strong> 3.8.2</p><p><em>urls are first-class APIs</em></p><h3>Introduction</h3><p>Urls are fundamental to the design and implementation of any web project but there importance are often overlooked, This write-up is a start of a series that analyse urls of open-source projects.</p><h3>Example — A Simple CRUD project</h3><p>Consider a simple CRUD project represented by the urls below. We will make use of django-style regular expression paths to denote url paths.</p><pre>url(https://medium.com/r&#39;^r&#39;^$&#39;#39;)                       # List all<br>url(https://medium.com/r&#39;^create/r&#39;^create/$&#39;#39;)                # Create<br>url(https://medium.com/r&#39;^(?P&lt;pk&gt;\d+)/$&#39;)           # Read<br>url(https://medium.com/r&#39;^(?P&lt;pk&gt;\d+)/edit/$&#39;)      # Update<br>url(https://medium.com/r&#39;^(?P&lt;pk&gt;\d+)/delete/$&#39;)    # Delete</pre><p>which can be thought of as being the below were characters inside ‘&lt;…&gt;’ denote named variables.</p><pre>/                    # List all<br>create/              # Create<br>&lt;pk&gt;/                # Read<br>&lt;pk&gt;/edit            # Update<br>&lt;pk&gt;/delete          # Delete</pre><p>Traditionally, the urls are processed by a handler, which attaches a callable to each url path, which returns a response; either an HttpResponse, TemplateResponse, JSONResponse etc.</p><p>In APIs, either a REST handler handles the urls, which makes it possible for certain queries to be done through javascript.</p><h4>Django callables for the above CRUD app</h4><p>The below are possible django callables that can be mapped to each url path.</p><pre>url(https://medium.com/r&#39;^r&#39;^$&#39;, <strong>index_view</strong>, name=&#39;home&#39;#39;,%20%3Cstrong%3Eindex_view%3C/strong%3E,%20name=&#39;home&#39;)                       <br>url(https://medium.com/r&#39;^create/r&#39;^create/$&#39;, <strong>create_view</strong>, name=&#39;create&#39;#39;,%20%3Cstrong%3Ecreate_view%3C/strong%3E,%20name=&#39;create&#39;)             <br>url(https://medium.com/r&#39;^(?P&lt;pk&gt;\d+)/$&#39;, <strong>detail_view</strong>, name=&#39;detail&#39;)        <br>url(https://medium.com/r&#39;^(?P&lt;pk&gt;\d+)/edit/$&#39;, <strong>update_view</strong>, name=&#39;update&#39;)   <br>url(https://medium.com/r&#39;^(?P&lt;pk&gt;\d+)/delete/$&#39;, <strong>delete_view</strong>, name=&#39;delete&#39;)</pre><p>Given an ORM model which powers the project.</p><pre>from django.db import models</pre><pre>class CrudData(models.Model):<br>  name        = models.CharField(max_length=20)<br>  description = models.CharField(max_length=255)<br>  content     = models.TextField()</pre><pre>  class Meta:<br>    ordering = (&#39;id&#39;,)<br>    <br>  def __str__(self):<br>    return self.name</pre><p>Then for the url paths, we have</p><p><strong>List all</strong></p><pre>from django.shortcuts import ( render,<br>     get_object_or_404)         # renders template and context<br>from .models import CrudData    # Assume CrudData is defined here.</pre><pre>def index_view(request):<br>   return render(request, &#39;crud/index.html&#39;, {<br>        &#39;posts&#39;: CrudData.objects.all() })</pre><p><strong>Create and Update</strong></p><p>Assuming we have a form rendering system and a messaging system,</p><pre>from django.forms import ModelForm  <br>from django.contrib import messages<br>from django.http import HttpResponseRedirect</pre><pre># Creates a form from model CrudData<br>  form_class = type(ModelForm)(&#39;CrudDataForm&#39;,(ModelForm,), {<br>    &#39;Meta&#39;: type(&#39;Meta&#39;, (), {<br>              &#39;model&#39;: CrudData,<br>               &#39;exclude&#39;: [], })<br>    })</pre><pre>def create_view(request):<br>  if request.method == &#39;POST&#39;:<br>    form = form_class(request.POST, request.FILES)<br>    if form.is_valid():<br>      new_obj = form.save()<br>      msg = &#39;&quot;CrudData&quot; created successfully&#39;<br>      messages.success(request, msg, fail_silently=True)<br>      return HttpResponseRedirect(&#39;/&#39;) </pre><pre>  else:<br>    form = form_class()</pre><pre>  return render(request, &#39;crud/create.html&#39;, {<br>                &#39;form&#39;: form })</pre><pre>def update_view(request, pk):<br>  obj = get_object_or_404(pk=pk)<br>  if request.method == &#39;POST&#39;:<br>    form = form_class(request.POST, request.FILES, <br>                      instance= obj)<br>    if form.is_valid():<br>      obj = form.save()<br>      msg = &#39;&quot;CrudData&quot; updated successfully&#39;<br>      messages.success(request, msg, fail_silently=True)<br>      return HttpResponseRedirect(&#39;/&#39;)</pre><pre>  else:<br>    form = form_class(instance=obj)<br>  <br>  return render(request, &#39;crud/create.html&#39;, {<br>                &#39;form&#39;: form })</pre><p><strong>Read</strong></p><pre>def detail_view(request, pk):<br>  return render(request, &#39;crud/detail.html&#39;, {<br>                &#39;post&#39;: get_object_or_404(pk=pk) })</pre><p><strong>Delete</strong></p><p>Assuming we have a messaging system,</p><pre>def delete_view(request, pk):<br>  obj = get_object_or_404(pk=pk)<br>  if request.method == &#39;POST&#39;:<br>    obj.delete()<br>    msg = &#39;&quot;CrudData&quot; object deleted successfully&#39;<br>    messages.success(request, msg, fail_silently=True)<br>    return HttpResponseRedirect(&#39;/&#39;)<br>  else:<br>    return render(request, &#39;crud/confirm_delte.html&#39;, {<br>                 &#39;object_name&#39;: obj, })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373b8558a1b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/urls-an-introduction-373b8558a1b8">urls — An Introduction</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Django Project on Heroku]]></title>
            <link>https://medium.com/django-framework-real-world-projects/deploy-django-project-on-heroku-13b191e311b6?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/13b191e311b6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Priyansh Singhal]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 04:05:06 GMT</pubDate>
            <atom:updated>2020-09-06T04:05:06.350Z</atom:updated>
            <content:encoded><![CDATA[<h4>Django, Heroku, Web Development</h4><h4>Take your Technical projects to next level.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkM3IHs8ejj-nrmZz1XQpA.jpeg" /></figure><p>As we know Django is python based open-source framework which follows MVC(Model View Controller) architectural pattern used in the rapid development of the website with clean design without worrying too much about setting up an environment to start.</p><p>I am using python 3.8.3 version and VS code as my text editor. deploying a Django project on Heroku is often difficult. To deploy it with ease some steps are needed to be followed :</p><ol><li><strong><em>Create a Heroku account</em></strong> :</li></ol><p>creating a Heroku account is very simple. visit <a href="https://dashboard.heroku.com/">https://dashboard.heroku.com/</a> so signup as a new account by tapping on signup button located in the top-right corner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELKVUG5DzkJK4wbCFKphgA.jpeg" /></figure><p>After successful signup and login proceed to next step.</p><p>2. <strong><em>Create a Django app</em></strong> :</p><p>create a fresh Django app using -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*LUTMqVVOEI3OaiDAkCHXvg.jpeg" /></figure><p>or you can use your project make sure you are inside your project folder where manage.py file is present.</p><p>3. <strong><em>Create a Virtual Environment and Install required dependencies</em></strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*GfalRzd8JHG7vTcHZa8GmQ.jpeg" /></figure><p>Install basic libraries using pip like pip install Django and most important install gunicorn(WSGI application server) and white noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myGoub98ifdY-6ZO8rLrfA.jpeg" /></figure><p>After installation of all libraries run the command :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*qGrgILs70smsQQryn4lZVw.jpeg" /></figure><p>It creates a new file in the root directory which consists of all libraries used in Django named requirements.txt which helps Heroku to install dependencies before deploying.</p><p>4. <strong><em>Create an App on Heroku site</em></strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOv6hSUi9StAfuL_cT_ZlQ.jpeg" /></figure><p>By clicking on creating new app add the name you want for your app then open settings tabs, tap on add build pack and tap on python to set python as your build pack and save changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*-266oVzDI7aIuUSbIZtjuw.jpeg" /></figure><p>5. <strong><em>Addition of required files</em></strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*Cqr5pz_hoZm-DS3-0DrWqQ.jpeg" /></figure><p>Now create two new files runtime.txt in which specify the version of python used and other Procfile with no extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*SCZNr37KwNdlvAPzys8Zfg.jpeg" /></figure><p>here gunicorn in place of vidz you need to enter your project folder name which contains settings.py file</p><p>5. Changes in settings.py file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6vgwaOR8RXbwO-RHybfDQ.jpeg" /></figure><p>Click on your Heroku project then tap on an open app button present in the top right corner it opens up the link where the project will be deployed. copy the link and paste it in settings.py allowed host section with local server to run it locally and change DEBUG to false as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*zOgo98p6zIXVDpem2ZGUag.jpeg" /></figure><p>Now add white noise as middleware in Django settings.py middleware section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*7p1vNADXGE_sC6G0BVORZg.jpeg" /></figure><p>Add STATIC_ROOT to configure static files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*ABR_rebL2loaTyRQ2_3ogg.jpeg" /></figure><p>6. <strong><em>Connect GitHub repository to Heroku</em></strong> :</p><p>After changes push the project to Github</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*Bc5HXyHKMxmed77eUM3OhA.jpeg" /></figure><p>In Heroku deploy section connect GitHub repository by tapping on connect to Github.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*qgmzWJdZVy4_YL539Vv_NA.jpeg" /></figure><p>After completion tap on deploy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*kcpkjcHpy_4ycfLCNDuGNg.jpeg" /></figure><p>Voila, Project is Deployed.</p><h4>Conclusion:</h4><p>Hopefully, this article about Django project deployment clears your imagination about deployment and also encourages you to learn more about web development.</p><p>Thank you so much for reading this, also share this article.</p><p>Feel free to connect:</p><blockquote><em>LinkedIN ~ </em><a href="https://www.linkedin.com/in/priyanshsinghal/">https://www.linkedin.com/in/priyanshsinghal/</a></blockquote><blockquote><em>Instagram ~ </em><a href="https://www.instagram.com/_daksh_trehan_/">https://www.instagram.com/18_priyansh/</a></blockquote><blockquote><em>Github ~ </em><a href="https://github.com/priyansh18">https://github.com/priyansh18</a></blockquote><p>Follow for more…</p><blockquote><em>Cheers.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b191e311b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/deploy-django-project-on-heroku-13b191e311b6">Deploy Django Project on Heroku</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuilding Django]]></title>
            <link>https://medium.com/django-framework-real-world-projects/rebuilding-django-65906bf0e222?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/65906bf0e222</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Sat, 02 May 2020 00:01:58 GMT</pubDate>
            <atom:updated>2020-05-02T14:54:25.843Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>updated</strong> for <strong>python 3.8.2 </strong>and<strong> django 2.2.12</strong></p><p><strong><em>et vincere nemo dividat, </em></strong><em>the experts say, Well I hear you but how do you conquer a project whose divided parts are as complex as the whole part?.</em></p><p>Django is large and powerful. Extensibility seems to be a guiding principle. The size of its <a href="https://docs.djangoproject.com/en/3.0/"><em>documentation</em></a> is scary but on a closer look, it is based on very simple concepts.</p><p>We will rebuild it using a top-down approach, utilizing the library till everything is rebuilt. Check the table of content below for guidiance.</p><h3>First Steps — Relying on django’s HTTP and URL systems</h3><p>Create a folder <em>M</em>. Create and activate a virtual environment in it. Intialize git, create files <em>README.md</em>, <em>manage.py</em> and <em>.gitinore</em></p><p>From the command line, install django 2.2.12 as shown below.</p><pre>python -m pip install django==2.2.12<br>python -m pip install -U pip</pre><p>In folder <em>M</em>, create sub-folder <em>project</em>. Im folder <em>M/project</em> create files <em>__init__.py</em>, <em>settings.py</em>, <em>urls.py</em>. You should have the below directory structure.</p><pre>M/<br>    project/<br>        __init__.py<br>        settings.py<br>        urls.py<br>    manage.py<br>    README.md</pre><p>Inside <em>M/manage.py</em>, we need to provide code to run django when the manage.py is called with valid django commands. This is shown below.</p><pre>import os<br>import sys</pre><pre>if __name__ == &#39;__main__&#39;:<br>    os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;,<br>                            &#39;project.settings&#39;)<br>    from django.core.management import execute_from_command_line<br>    execute_from_command_line(sys.argv)</pre><p>At the most fundamental level, django requires a root settings configuration file and a root url configuration file.</p><p>Inside <em>M/project/settings.py</em>, input the below code</p><pre>DEBUG = True<br>SECRET_KEY = &#39;#a39sfad9&#39;      # You can put anything for now.<br>ROOT_URLCONF = &#39;project.urls&#39;</pre><p>Inside <em>M/project/urls.py</em>, input the below code</p><pre>from django.urls import re_path<br>from django.http import HttpResponse</pre><pre>urlpatterns = [<br>    re_path(r&#39;^$&#39;, lambda request: HttpResponse(&#39;Welcome home&#39;)),<br>    re_path(r&#39;^path/$&#39;, lambda request: HttpResponse(<br>        request.path)),<br>    re_path(r&#39;^method/$&#39;, lambda request: HttpResponse(<br>        request.method)),<br>    re_path(r&#39;^get_host/$&#39;, lambda request: HttpResponse(<br>        request.get_host()),<br>]</pre><p>Power up your server with</p><pre>python manage.py runserver</pre><p>Check the paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*h0uHbYzUi9azKZS-BTFmpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*xMRU3Drsm-qpa3C4x-qmYg.png" /></figure><p>If you are observant, you will notice that if you call the path without appending slash it screams at you as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*qynm9RE1bTZJUdQj8dSbqQ.png" /></figure><p>To solve this problem, meet middlewares.</p><p>Middlewares like hackers that want to steal your confidential details intercept the request and response model and performs certain actions or cetain alterations to either the request or response or both or something else like a view etc.</p><p>We will just use django’s solution for now, latter we will rebuilt it (because we are awesome).</p><p>Edit <em>M/project/settings.py </em>to include MIDDLEWARE as shown below.</p><pre>DEBUG = True<br>SECRET_KEY = &#39;#a39sfad9&#39;    # You can put anything for now<br>ROOT_URLCONF = &#39;project.urls&#39;<br>MIDDLEWARE = [&#39;django.middleware.common.CommonMiddleware&#39;]</pre><p>Retry the paths without append slash again and it magically appends slash.</p><p><strong>Remembering Git</strong></p><p>Lest we forget, big brother git is waiting for us. Project M can be found on github here.</p><pre>git add .<br>git commit -m &quot;first project commit. Loving it.&quot;<br>git push origin master</pre><h4>Brief Explanation of the Above</h4><p>Like any real web framework, support for handling http request and response must be provided. A url mapping system is also provided. A configuration file to customise different parts of the framework is also provides.</p><p>A web application receives http request and returns http response which is what we did above.</p><h3>Table of Content</h3><p>The project shall follow this pattern.</p><h4>First projects</h4><ol><li>Introduction to django views — FBV and GFBV</li><li>Deeper look into django views — CBV and GCBV</li><li>Rebuilding django oscar ecommerce</li><li>A glance at Middlewares</li><li>Rebuilding django.contrib.sites</li><li>Rebuilding django.contrib.contenttypes</li><li>Rebuilding django.contrib.messages</li><li>Rebulding django.contrib.sessions</li><li>Rebuilding django.contrib.auth</li><li>Rebuilding django.contrib.admin</li><li>Rebuilding mezzanine</li><li>Rebuilding cartridge</li><li>Rebuilding django rest framework</li><li>Rebuilding ariadne.</li></ol><h4>Second Projects</h4><ol><li>Rebuilding django’s http</li><li>Rebuilding django’s urls</li><li>Rebuilding django’s caching system</li><li>Rebuilding django’s file storage system</li><li>Rebuilding django’s ORM</li><li>Rebuilding django’s Form rendering system</li><li>Rebuilding django’s mail system.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65906bf0e222" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/rebuilding-django-65906bf0e222">Rebuilding Django</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Syntax, Semantics and Standard Library — Syntactic Convention]]></title>
            <link>https://medium.com/django-framework-real-world-projects/python-syntax-semantics-and-standard-library-syntactic-convention-f0f7c2f54c0b?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/f0f7c2f54c0b</guid>
            <category><![CDATA[grammar]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 11:59:13 GMT</pubDate>
            <atom:updated>2020-04-24T13:34:50.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python: Syntax, Semantics and Standard Library — Syntactic Convention</h3><p><strong>updated</strong> for <strong>python 3.8.2</strong></p><p><em>We should all aspire to be programmers like the experts of old and the experts of today.</em></p><p><em>Web development has many beautiful algorithms, I think I am in love.</em></p><p><a href="https://medium.com/django-framework-real-world-projects/python-syntax-semantics-and-standard-library-f3dbee7a5078?source=extreme_sidebar----86ab17bb8091-----0-1----------------------"><strong>&lt;&lt; previous</strong></a> | next &gt;&gt;</p><p>This write-up continues from <a href="https://medium.com/django-framework-real-world-projects/python-syntax-semantics-and-standard-library-f3dbee7a5078?source=extreme_sidebar----86ab17bb8091-----0-1----------------------">Python: Syntax, Semantics and Standard Library</a>.</p><h3>Note</h3><p>The <a href="https://docs.python.org/3/">python documentation</a> remains a major source of information. What is presented here is just a condensed form of what is found there subject to my understanding.</p><h3>Introduction</h3><p>Over the years, different design paradigms have been proposed to help programmers cope with real-world problems.</p><p>The <em>concept of identifiers</em> and its<em> limited scope</em> as proposed by ALGO 60, the <em>concept of functions</em>, the <em>concept of modules</em> and its idea of <em>information hiding</em>, where identifiers from other modules must be <em>imported</em> before they can be used.</p><p>The concept of <em>extending</em> <em>record</em> or <em>structure types</em> through <em>inheritance</em> and also creating <em>user-defined type</em>s that<em> support operations like built-in types</em> using <em>methods</em> (which are functions bound to these user-defined types) as proposed by the object-oriented paradigm.</p><p>In this write-up, I use a top-down approach to represent the different thoughts.</p><h3>Object as an abstraction of data</h3><p>Object is python’s abstraction for data. Python provides the built-in <em>object</em> which serves as base for all classes.</p><p>Every object has an identity, a type and a value. The identity can be thought of as its memory address. The built-in function <strong><em>id</em></strong> returns an integer representing an objects identity. The <strong><em>is</em></strong> operator compares the identity of two objects. The identity of an object is unchangeable.</p><p>The type of an object determines the operations that can be performed on it. The type of an object is unchangeable.</p><p>The value of an object can change if it is mutable. Note that the value of an immutable container object can change if it references a mutable object as member, whose value is changed. An objects mutability is determined by its type.</p><pre>&gt;&gt;&gt; object             # Python, what is &#39;object&#39; ?<br>&lt;class &#39;object&#39;&gt;<br>&gt;&gt;&gt; <br>&gt;&gt;&gt; id(object)         # What is the identity of object ?<br>1932901240<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(object)       # What is type of object ?<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt; x = object<br>&gt;&gt;&gt; x is object<br>True<br>&gt;&gt;&gt; x = object()<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; x                  # What is &#39;x&#39; ?<br>&lt;object object at 0x011166B0&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; id(x)              # What is identity of &#39;x&#39; ?<br>17917616<br>&gt;&gt;&gt; type(x)            # What is type of x<br>&lt;class &#39;object&#39;&gt;</pre><pre>&gt;&gt;&gt; object                # Is a type object<br>&lt;class &#39;object&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; object.__class__<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; object.__name__<br>&#39;object&#39;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; object.__mro__<br>(&lt;class &#39;object&#39;&gt;,)<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; object.__bases__<br>()<br>&gt;&gt;&gt; x = object()     # instance of object, not a type object<br></pre><p>The <em>__class__</em> of an object is the same as its type which can be accessed using the type constructor that accepts an <em>object</em>.</p><pre>&gt;&gt;&gt; object.__class__<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(object)<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; int.__class__<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(int)<br>&lt;class &#39;type&#39;&gt;</pre><h3>Modules</h3><p>Python supports modular design by default. Every file which has the ‘.py’ extension and contains well-formed code according to the syntax below, is a module. The name before the ‘.py’ must be a valid identifier.</p><pre>file_input      := {NEWLINE | stmt} ENDMARKER .<br>stmt            := simple_stmt | compount_stmt .<br>compount_stmt   := classdef | funcdef | decorated | async_stmt |<br>                   if_stmt | while_stmt | for_stmt | try_stmt |<br>                   with_stmt .<br>simple_stmt     := small_stmt { &quot;;&quot; small_stmt } [&quot;;&quot;] NEWLINE .<br>small_stmt      := import_stmt | global_stmt | nonlocal_stmt |<br>                   assert_stmt | expr_stmt | del_stmt |<br>                   pass_stmt | flow_stmt .</pre><h4>Importing a module — the import_statement</h4><p>A module can be imported using the <em>import statement</em> which is described in <em>EBNF</em> below.</p><pre>import_stmt     := import_name | import_from .<br>import_name     := &quot;import&quot; dotted_as_names .<br>import_from     := &quot;from&quot; ({&quot;.&quot; | &quot;...&quot;} dotted_name |<br>                   (&quot;.&quot; | &quot;...&quot;){&quot;.&quot; | &quot;...&quot;})<br>                   &quot;import&quot; (&quot;*&quot; | &quot;(&quot; import_as_names &quot;)&quot; |<br>                   import_as_names) .<br>dotted_as_names := dotted_as_name {&quot;,&quot; dotted_as_name} .<br>dotted_as_name  := dotted_name [&quot;a&quot; identifier]<br>dotted_name     := identifier {&quot;.&quot; identifier} .<br>import_as_names := import_as_name {&quot;,&quot; import_as_name} [&quot;,&quot;] .<br>import_as_name  := identifier[&quot;as&quot; identifier] .</pre><p>Consider a module denoted by the file <em>ezenwanyi.py</em>, with the below definitions and statements.</p><pre>&quot;&quot;&quot; This is just a test module &quot;&quot;&quot;</pre><pre>a = &quot;Chidi is a boy&quot;<br>b = &quot;Amarachi is a girl.&quot;<br>c = a + &quot; and &quot; + b<br>d = 3<br>e = d ** 4</pre><p>Attribute <em>x</em> in a module <em>M</em> can be accessed as <em>M.x</em></p><p>The built-in function <em>dir()</em> can be used to find out which names a module defines. Let us play around in the python interpreter.</p><pre>&gt;&gt;&gt; import ezenwanyi      # import module &#39;ezenwanyi&#39; .   <br>&gt;&gt;&gt; ezenwanyi.a<br>&#39;Chidi is a boy&#39;<br>&gt;&gt;&gt; ezenwanyi.c<br>&#39;Chidi is a boy and Amarachi is a girl.&#39;<br>&gt;&gt;&gt; ezenwanyi.e<br>81<br>&gt;&gt;&gt; from ezenwanyi import a, b, e   # import &#39;a&#39;, &#39;b&#39;, &#39;c&#39;<br>&gt;&gt;&gt; a<br> &#39;Chidi is a boy&#39;<br>&gt;&gt;&gt; b<br>&#39;Amarachi is a girl.&#39;<br>&gt;&gt;&gt; from ezenwanyi impor c as ab    <br>&gt;&gt;&gt; ab<br>&#39;Chidi is a boy and Amarachi is a girl.&#39;<br>&gt;&gt;&gt; from ezenwanyi import *        # import all<br>&gt;&gt;&gt; a<br>&#39;Chidi is a boy&#39;</pre><p>A python module has identifiers like the <em>__name__</em>, <em>__file__</em>, <em>__dict__</em>, <em>__doc__ </em>etc which has special meaning. Don’t forget that modules are also objects in python.</p><pre>&gt;&gt;&gt; import ezenwanyi<br>&gt;&gt;&gt; ezenwanyi.__name__     # name of module<br>&#39;ezenwanyi&#39;<br>&gt;&gt;&gt; ezenwanyi.__file__     # Where it is store.<br>&#39;C:\\a\\ezenwanyi.py&#39;<br>&gt;&gt;&gt; ezenwanyi.__doc__      # docstring<br>&#39; This is just a module &#39;<br>&gt;&gt;&gt; ezenwanyi.__dict__     #dictionary mapping attributes to values</pre><p>Modules can also be imported using the <em>importlib</em> module and the <em>__module__ </em>function.</p><h4>Executing modules as scripts.</h4><p>A python module is a complete program, it is executed in an environment where all built-in and standard modules are available but not initialized except for <em>sys</em>, <em>builtins</em> and <em>__main__ </em>modules. The <em>__main__</em> module is used as the local and global namespace for the execution of the complete program. Consider the module <em>execute_module.py</em> below:</p><pre>&quot;&quot;&quot; A simple module that test script execution. &quot;&quot;&quot;</pre><pre>import sys</pre><pre>def f():<br>    return &quot;Hello world&quot;</pre><pre>if __name__ == &quot;__main__&quot;:<br>  print(f(), sys.argv)</pre><p>We can execute the script from terminal using the format:</p><pre>python execute_module.py &lt;arguments&gt;</pre><p>Thus we have</p><pre>C:\a&gt;python execute_module.py 23 4<br>Hello world [&#39;execute_module.py&#39;, &#39;23&#39;, &#39;4&#39;]</pre><p>We can see that the built in <em>sys.argv</em>, gives us the entered arguments as a list starting with the script name.</p><h4>Packages</h4><p>Python packages are directories containing python files and possibly other directories. Each directory must have a <em>__init__.py </em>file which sometimes contains values. For example consider a simple package.</p><pre>django/<br>      core/<br>          __init__.py<br>          filestorage.py<br>          mail.py<br>      utils/<br>          __init__.py<br>          trees.py<br>          decorators.py<br>      __init__.py</pre><h4>Importing from Packages</h4><p>Given a <em>directory</em> <em>M</em> and <em>subdirectories A, B, C</em> . The <em>directory B</em> have <em>subdirectories D, E. </em>The<em> directory D </em>has files <em>a.py</em>, <em>c.py</em>, <em>d.py</em>. The <em>file d</em> has functions <em>a, b, c</em>. Remember that directories are required to have <em>__init__.py</em> file. You can specify the modules you want to import in the list <em>__all__</em> when the “*” is used in <em>__init__.py</em>.</p><pre>&gt;&gt;&gt; from M.B.D import d      # import module d<br>&gt;&gt;&gt; from M.B.D.d import a    # import function a<br>&gt;&gt;&gt; from M import * </pre><h3>Class</h3><p>Python implements the object-oriented paradigm using class statements.</p><pre>classdef      := &quot;class&quot; NAME [&quot;(&quot; [arglist] &quot;)&quot; ] &quot;:&quot; suite .<br>arglist       := argument {&quot;,&quot; argument} [&quot;,&quot;] .<br>argument      := test [comp_for] | test &quot;:= test | <br>                 test &quot;=&quot; test | &quot;**&quot; test | &quot;*&quot; test .<br>suite         := simple_stmt | NEWLINE INDENT stmt {stmt} DEDENT .</pre><p>A class can be created using the class statement. A class is a callable, calling it (class instantiation) creates an instance which is also an object.</p><p>Inheritance is used to either extend or overide the attributes and methods of a parent class.</p><p>Check out the <a href="https://docs.python.org/3/reference/datamodel.html#special-method-names"><em>python documentation</em></a> for more information on classes.</p><pre>&gt;&gt;&gt; class C:            # Class definition<br>...     pass<br>...<br>&gt;&gt;&gt; C<br>&lt;class &#39;__main__.C&#39;&gt;<br>&gt;&gt;&gt; C()<br>&lt;__main__.C object at 0x00CCF838&gt;<br>&gt;&gt;&gt; C().__class__<br>&lt;class &#39;__main__.C&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; class A:<br>...     pass<br>...<br>&gt;&gt;&gt; class D(A):         # Single Inheritance<br>...     pass<br>...<br>&gt;&gt;&gt; D.__mro__           # Method resolution order<br>(&lt;class &#39;__main__.D&#39;&gt;, &lt;class &#39;__main__.A&#39;&gt;, &lt;class &#39;object&#39;&gt;)<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; class E(D, C):      # Multiple Inheritance<br>...     pass<br>...<br>&gt;&gt;&gt; E.__mro__<br>(&lt;class &#39;__main__.E&#39;&gt;, &lt;class &#39;__main__.D&#39;&gt;, &lt;class &#39;__main__.A&#39;&gt;, <br>&lt;class &#39;__main__.C&#39;&gt;, &lt;class &#39;object&#39;&gt;)<br>&gt;&gt;&gt;</pre><h4>Special method names — A First Example</h4><p>Python provides methods with special names to aid in the implementation of certain operations like arithmetic operations, dictionary-style access, comparisons etc.</p><p>Consider a code fragment from django’s <em>MultiValueDict</em> dictionary.</p><pre>&gt;&gt;&gt; class MultiValueDictKeyError(KeyError):<br>...     pass <br>...<br>&gt;&gt;&gt; class MultiValueDict(dict):<br>...     &quot;&quot;&quot;<br>...     A dictionary customized to handle multiple values <br>...     for the same key.<br>...     &quot;&quot;&quot;<br>...     def __init__(self, key_to_list_mapping=()):<br>...         super().__init__(key_to_list_mapping)<br>...     def __repr__(self):<br>...         return &quot;&lt;%s: %s&gt;&quot; % (self.__class__.__name__, <br>...                 super().__repr__())<br>...     def __getitem__(self, key):<br>...         &quot;&quot;&quot;<br>...         Returns the last data value for this key. If not <br>...         found, raise KeyError. Return [] if empty<br>...         &quot;&quot;&quot;<br>...         try:<br>...             list_ = super().__getitem__(key)<br>...         except KeyError:<br>...             raise MultiValueDictKeyError(key)<br>...         try:<br>...             return list_[-1]<br>...         except IndexError:<br>...             return []<br>...     def __setitem__(self, key, value):<br>...         super().__setitem__(key, [value])<br>...     def __copy__(self):<br>...         return self.__class__([<br>...             (k, v[:]) for k, v in self.lists() ])<br>...     def lists(self):<br>...         &quot;&quot;&quot;Yield (key, list) pairs.&quot;&quot;&quot;<br>...         return iter(super().items())<br>...<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; d = MultiValueDict({&#39;name&#39;:[&#39;Obi&#39;,&#39;Madu&#39;], &#39;age&#39;:[&#39;30&#39;]})<br>&gt;&gt;&gt; d[&#39;name&#39;]<br>&#39;Madu&#39;<br>&gt;&gt;&gt; d[&#39;age&#39;] = 29<br>&gt;&gt;&gt; d[&#39;age&#39;]<br>29<br>&gt;&gt;&gt; repr(d)<br>&quot;&lt;MultiValueDict: {&#39;name&#39;: [&#39;Obi&#39;: &#39;Madu&#39;], &#39;age&#39;: [29]}&gt;&quot;<br>&gt;&gt;&gt; repr(MultiValueDict)<br>&quot;&lt;class &#39;__main__.MultiValueDict&#39;&gt;&quot;<br>&gt;&gt;&gt;</pre><p>As you can see above,</p><p>The __getitem__() special method name allows ass to provide array-like accessor on the dict, thus we can perform <em>instance[key]. </em>The<em> __setitem__()</em> special method name sets values to it.</p><p>Python has many special methods that perform varying operations. Check the <a href="https://docs.python.org/3/reference/datamodel.html#special-method-names"><em>Special method name</em></a> for more information.</p><h4>Getters and Setters — property type to the rescue</h4><p>Data abstraction and data encapsulation are big terms in the OOP world. The idea is to make the attributes private and present the attributes of a class through methods. For example</p><pre>class C:<br>    def __init__(self, name, age):<br>        self.__name = name<br>        self.__age = age<br>    <br>    def set_name(self, name):<br>        self.__name = name</pre><pre>    def get_name(self):<br>        return self.__name</pre><pre>    def set_age(self, age):<br>        self.__age = age<br>    <br>    def get_age(self):<br>        return self.__age</pre><p>We can access them as</p><pre>&gt;&gt;&gt; x = C(&quot;Obi&quot;, 23)<br>&gt;&gt;&gt; x.get_name()<br>&#39;Obi&#39;<br>&gt;&gt;&gt; x.get_age()<br>23<br>&gt;&gt;&gt; x.set_name(&quot;Chidi&quot;)<br>&gt;&gt;&gt; x.get_name()<br>&#39;Chidi&#39;</pre><p>We can see that just for two attributes name and age, we have defined four methods to access them. If we introduce new attribues, the access methods increases. This is unacceptable.</p><p>Well, we can just access the attributes directly, since changing them won’t really break any invariant. Thus we design our class like this.</p><pre>class C:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age</pre><p>We can access them as</p><pre>&gt;&gt;&gt; x = C(&quot;Obi&quot;, 23)<br>&gt;&gt;&gt; x.name <br>&#39;Obi&#39;<br>&gt;&gt;&gt; x.age<br>23<br>&gt;&gt;&gt; x.age = 30<br>&gt;&gt;&gt; x.age<br>&gt;&gt;&gt; 30</pre><p><strong><em>property</em> type</strong></p><p>What if we want to, say access values from another source before returning the attribute, perform certain operations before mutating an attribute, or just returning methods as attributes, the <em>property</em> type comes to rescue.</p><pre>&gt;&gt;&gt; class C:<br>...     def _print_name(self):<br>...         return &quot;Hello %s&quot; % self.__class__.__name__<br>...     x = property(_print_name)<br>...<br>&gt;&gt;&gt; C().x<br>&#39;Hello C&#39;<br>&gt;&gt;&gt; C.x<br>&lt;property object at 0x0234B460&gt;<br>&gt;&gt;&gt;</pre><h4>Instance methods, classmethod type and staticmethod type</h4><p>Instance methods take an instance of the class a first argument usually named <em>self</em>. They can modify both instance and class state. They can access identifiers which any instance object can access like the __class__ and __dict__ names etic.</p><pre>&gt;&gt;&gt; class R:<br>...     def __init__(self, name):<br>...         self.name = name<br>...     def print_name(self):<br>...         print(&quot;My name is &quot;, self.name)<br>...<br>&gt;&gt;&gt; R.print_name(R(&quot;Chidi&quot;))<br>My name is Chidi<br>&gt;&gt;&gt; x = R(&quot;Ada&quot;)<br>&gt;&gt;&gt; x.print_name()<br>My name is Ada</pre><p>Class methods take as first argument the class. As a result, they can modify attributes of instance objects. The <em>classmethod()</em> type is used to create them.</p><p>Static methods do not take either an instance of the class or the class as argument. As a consequence, they cannot modify both class state and instance state. The <em>staticmethod()</em> type is used to create them.</p><p>Consider a class Record below</p><pre>class Record:<br>    <br>    def __init__(self, name, age, sex):<br>        self.name = name <br>        self.age = age<br>        self.sex = sex</pre><pre>    def new_klass(cls, name, age, sex):<br>        return cls(name, age, sex)<br>    <br>    def free_func():<br>        return &quot;I am a free function&quot;</pre><pre>    new_klass = classmethod(new_klass)<br>    free_func = staticmethod(free_func)</pre><p>We can use record as</p><pre>&gt;&gt;&gt; R = Record(&quot;Obi&quot;, 23, &quot;Male&quot;)<br>&gt;&gt;&gt; R.name<br>&#39;Obi&#39;<br>&gt;&gt;&gt; B = Record.new_klass(&quot;Beatrice&quot;, 24, &quot;Female&quot;)<br>&gt;&gt;&gt; B.name<br>&#39;Beatrice&#39;<br>&gt;&gt;&gt; B.sex<br>&#39;Female&#39;<br>&gt;&gt;&gt;</pre><h4>Descriptors</h4><p>Descriptors are used to overide attribute access with methods defined in the descriptor protocol. If an object defines any of the below methods, it is a descriptor.</p><pre>descr.__get__(self, obj, type=None) -&gt; value<br>descr.__set__(self, obj, value) -&gt; None<br>descr.__delete__(self, obj) -&gt; None</pre><p>If an object defines both <em>__set__()</em> and <em>__delete__()</em> method, it is considered a data descriptor. If it defines only <em>__get__()</em> method, it is considered a non-data descriptor. <em>classmethod()</em> and <em>staticmethod()</em> are implemented as non-data descriptors, while <em>property()</em> is implemented as a data descriptor.</p><p>More about descriptors can be learned at <a href="https://docs.python.org/3/howto/descriptor.html"><em>Descriptor HowTo Guide.</em></a></p><p>Consider a simple non-data descriptor below.</p><pre>&gt;&gt;&gt; class my_property:<br>...     def __init__(self, method):<br>...         self.fget = method<br>...         self__doc__ = getattr(method, &#39;__doc__&#39;)<br>...     def __get__(self, instance, cls=None):<br>...         if instance is None:<br>...             return self<br>...         return self.fget(instance)<br>...<br>&gt;&gt;&gt; <br>&gt;&gt;&gt; # With it, we can use methods as attributes<br>&gt;&gt;&gt; class C:<br>...     def _print_name(self):<br>...         return &quot;Hello %s&quot; % self.__class__.__name__<br>...     print_name = my_property(_print_name)<br>...<br>&gt;&gt;&gt;<br>&gt;&gt;&gt;  C().print_name<br>&#39;Hello C&#39;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; C.print_name<br>&lt;__main__.my_property object at 0x00C9F718&gt;<br>&gt;&gt;&gt;</pre><h4>Metaclass</h4><p>To create a new style class, you either inherit from <em>object </em>or <em>type</em>. Inheriting from <em>type</em> creates a <em>metaclass</em>. Just as calling a class creates an instance which is also an object, calling a metaclass creates a class which is also an object(and also a type).</p><pre>&gt;&gt;&gt; class C(object):       # Is inherited implicitly<br>...     pass<br>...<br>&gt;&gt;&gt; C<br>&lt;class &#39;__main__.C&#39;&gt;<br>&gt;&gt;&gt; C.__bases__<br>(&lt;class &#39;object&#39;&gt;,)<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; class M(type):<br>...     pass<br>...<br>&gt;&gt;&gt; M<br>&lt;class &#39;__main__.M&#39;&gt;<br>&gt;&gt;&gt; M.__bases__<br>(&lt;class &#39;type&#39;&gt;,)</pre><p>Metaclass can be used to control the creation behaviour of classes. For example using metaclass <em>M</em> above, we can add more attributes to class <em>C</em> using the <em>__new__(cls, name, bases, attrs)</em> method.</p><p>An example is given below</p><pre>&gt;&gt;&gt; class M(type):<br>...     def __new__(cls, name, bases, attrs):<br>...         attrs.update({&#39;first_name&#39;: &#39;Obi&#39;, <br>...                 &#39;last_name&#39;: &#39;Madu&#39;})<br>...         return super(M, cls).__new__(cls, name, bases, attrs)<br>...<br>&gt;&gt;&gt; <br>&gt;&gt;&gt; class C(metaclass=M):<br>...     pass<br>...<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; C.first_name<br>&#39;Obi&#39;<br>&gt;&gt;&gt; C.last_name<br>&#39;Madu&#39;<br>&gt;&gt;&gt;</pre><p>Special method names applicable to metaclass can be found at <a href="https://docs.python.org/3/reference/datamodel.html#metaclasses"><em>Metaclasses</em></a>.</p><h3>Functions</h3><p>Functions denote action. There syntax in EBNF is describe below</p><pre>funcdef         := &quot;def&quot; identifier parameters [&quot;-&gt;&quot; test] &quot;:&quot;<br>                   [TYPE_COMMENT] func_body_suite .<br>func_body_suite := simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] <br>                   INDENT stmt {stmt} DEDENT .<br>parameters      := &quot;(&quot; [typedargslist] &quot;)&quot; .<br>typedargslist   := </pre><p>Functions are also object as shown below.</p><pre>&gt;&gt;&gt; def f():<br>...     pass<br>...<br>&gt;&gt;&gt; f                       # what is &#39;f&#39; ?<br>&lt;function f at 0x00557808&gt;<br>&gt;&gt;&gt; type(f)                 # what is &#39;type(f)&#39; ?<br>&lt;class &#39;function&#39;&gt;<br>&gt;&gt;&gt; f()                     # function call<br>&gt;&gt;&gt; def f():<br>...     print(&quot;Hello world&quot;)<br>...<br>&gt;&gt;&gt; f()<br>Hello world<br>&gt;&gt;&gt; g = f                   # Assign f to g<br>&gt;&gt;&gt; g()<br>Hello world</pre><h4>Defining functions inside function</h4><p>Class types and other functions can be defined inside a function according to the syntax described above. This is shown below</p><pre>&gt;&gt;&gt; def f():<br>...     def g():<br>...         print(&quot;Hello world&quot;)<br>...     g()<br>...<br>&gt;&gt;&gt; f()<br>Hello world</pre><h4>Returning objects from functions</h4><p>Objects can bereturned from functions as shown below.</p><pre>&gt;&gt;&gt; def f():<br>...     return &quot;Hello world&quot;<br>...<br>&gt;&gt;&gt; f()<br>&#39;Hello world&#39;<br>&gt;&gt;&gt; def f():<br>...     def g():<br>...         return &quot;Hello world&quot;<br>...     return g<br>...<br>&gt;&gt;&gt; f()<br>&lt;function f.&lt;locals&gt;.g at 0x0061E148&gt;<br>&gt;&gt;&gt; f()()                              # Calls g()<br>&#39;Hello world&#39;</pre><h4>Passing arguments to a Function</h4><p>A function can be passed objects as argument. The arguments can be positional argument and keyword argument. This is shown below</p><pre>&gt;&gt;&gt; def f(a, b):<br>...    return a + b<br>...<br>&gt;&gt;&gt; f(4, 3)<br>7<br>&gt;&gt;&gt;</pre><p><strong>passing positional arguments</strong></p><p>Variable number of positional arguments can be passed if the function is defined as follows</p><pre>&gt;&gt;&gt; def f(*args):<br>...    return sum(args)<br>...<br>&gt;&gt;&gt; f(2, 3, 4)<br>9<br></pre><p>Positional arguments can be gotten from a sequence as shown below.</p><pre>&gt;&gt;&gt; def f(*args):<br>...     return sum(args):<br>...<br>&gt;&gt;&gt; a = [1, 2, 3, 4]        # a list<br>&gt;&gt;&gt; f(*a)<br>10<br>&gt;&gt;&gt; b = (2, 3, 4, 5, 2)     # a tuple<br>&gt;&gt;&gt; f(*b)<br>16</pre><p><strong>passing keyword arguments</strong></p><p>Variable number of keyword arguments can be passed as shown below.</p><pre>&gt;&gt;&gt; def f(**kwargs):<br>...     return kwargs<br>...<br>&gt;&gt;&gt; f(a=2, b=3, c=4)<br>{&#39;a&#39;: 2, &#39;b&#39;: 3, &#39;c&#39;: 4}<br>&gt;&gt;&gt; </pre><p>Keyword arguments can be gotten from a dictionary as shown below</p><pre>&gt;&gt;&gt; def f(**kwargs):<br>...     return kwargs<br>...<br>&gt;&gt;&gt; b = {&#39;a&#39;: 2, &#39;b&#39;: 3, &#39;c&#39;: 4}<br>&gt;&gt;&gt; f(**b)<br>{&#39;a&#39;: 2, &#39;b&#39;: 3, &#39;c&#39;: 4}<br>&gt;&gt;&gt;</pre><h3>Decorators</h3><p>Functions can return callables (for example, other function objects). Functions can also accept function objects as arguments.</p><p>Anything that can accept a callable and return an object which is also a callable in the case of function or accepts a callable and defines a callable in the case of class objects, can benefit from the decorator syntax and semantics.</p><p>A decorator doesn’t have to return a callable though most decorators usually return functions. A class object or type which accepts a callable and defines a <em>__call__()</em> special method can also be used as a decorator.</p><p>Non-data descriptors that implement the<em> __get__()</em> special method can also be used as decorators. Data descriptors that implement the <em>getter()</em>, <em>setter()</em> as popularized by the <em>property</em> type can also be used as decorators.</p><p>Decorators works on class and functions alike.</p><p>The decorator syntax is as follows</p><pre>decorators  := decorator {decorator} .<br>decorator   := &quot;@&quot; dotted_name [ &quot;(&quot; [arglist] &quot;)&quot; ] NEWLINE .</pre><p><em>property()</em>, <em>classmethod()</em> and <em>staticmethod()</em> types can now be used as decorators.</p><p>Consider a simple use of property as a decorator below.</p><pre>&gt;&gt;&gt; class C:<br>...     @property<br>...     def x(self):<br>...         return &quot;Hello %s&quot; % self.__class__.__name__<br>...<br>&gt;&gt;&gt; C().x<br>&#39;Hello C&#39;<br>&gt;&gt;&gt;</pre><p>Consider a simple non-data descriptor below that can be used as a decorator.</p><pre>&gt;&gt;&gt; class my_property:<br>...     def __init__(self, method):<br>...         self.fget = method<br>...         self.__doc__ = getattr(method, &#39;__doc__&#39;)<br>...     def __get__(self, instance, cls=None):<br>...         if instance is None:<br>...             return self<br>...         return self.fget(instance)<br>...<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; class C:<br>...     @my_property<br>...     def x(self):<br>...         return &quot;Hello %s&quot; % self.__class__.__name__<br>...<br>&gt;&gt;&gt; C().x<br>&#39;Helo C&#39;<br>&gt;&gt;&gt;</pre><h3>Other Compound Statements</h3><p>Python provides other compound statments for different actions like repetition, conditionals etc.</p><h4>If Statement</h4><p>If statement is a conditional statement. It is described in EBNF as</p><pre>if_stmt     := &quot;if&quot; namedexpr_test &quot;:&quot; suite <br>               {&quot;elif&quot; namedexpr_test &quot;:&quot; suite}<br>               [&quot;else&quot; &quot;:&quot; suite] .</pre><p>Below is an example.</p><pre>&gt;&gt;&gt; a = 3<br>&gt;&gt;&gt; if a &gt; 2:<br>...     print(&quot;Yes&quot;)<br>... else:<br>...     print(&quot;No&quot;)<br>...<br>Yes<br>&gt;&gt;&gt;</pre><h4>While Statement</h4><p>While statment is a repetitive statment. It performs an action as long as the expression is True.</p><pre>while_stmt     := &quot;while&quot; namedexpr_test &quot;:&quot; suite<br>                  [&quot;else&quot; &quot;:&quot; suite] .</pre><p>An example is shown below</p><pre>&gt;&gt;&gt; i, n = 0, 10<br>&gt;&gt;&gt; while i &lt; n:<br>...     print(i**2)<br>...     i=i+1<br>...<br>0<br>1<br>4<br>9<br>16<br>25<br>36<br>49<br>64<br>81<br>&gt;&gt;&gt;</pre><h4>For Statement</h4><p>The for statement iterates over an iterable (for example, sequence types like lists, tuples, strings etc). Its syntax using EBNF is given below</p><pre>for_stmt    := &quot;for&quot; exprlist &quot;in&quot; testlist &quot;:&quot; [TYPE_COMMENT]<br>               suite [&quot;else&quot; &quot;:&quot; suite] .</pre><p>An example is shown below</p><pre>&gt;&gt;&gt; for x in [&quot;obi&quot;, &quot;chidi&quot;, &quot;ada&quot;, &quot;amarachi&quot;]:<br>...     print(x)<br>...<br>obi<br>chidi<br>ada<br>amarachi<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; state = {&quot;abia&quot;: &quot;umuahia&quot;, &quot;imo&quot;: &quot;owerri&quot;, &quot;enugu&quot;: &quot;enugu&quot;}<br>&gt;&gt;&gt; for key, value in state.items():<br>...     print(key, &quot; =&gt; &quot;, value)<br>...<br>abia =&gt; umuahia<br>imo =&gt; owerri<br>enugu =&gt; enugu<br>&gt;&gt;&gt;</pre><h4>Try Statement</h4><p>The try statment is used to handle exceptions. The syntax in EBNF is given below:</p><pre>try_stmt      := &quot;try&quot; &quot;:&quot; suite <br>                 (except_clause &quot;:&quot; suite {except_clause &quot;:&quot; suite}<br>                 [&quot;else&quot; &quot;:&quot; suite] [&quot;finally&quot; &quot;:&quot; suite] |<br>                 &quot;finally&quot; &quot;:&quot; suite) .<br>except_clause := &quot;except&quot; [test [&quot;as&quot; identifier]] .</pre><p>This can be shown by the expression below.</p><pre>&gt;&gt;&gt; try:<br>...     print(&quot;There is no exception here.&quot;)<br>... except:<br>...     print(&quot;There is an exception here.&quot;)<br>... finally:<br>...     print(&quot;Please continue.&quot;)<br>...<br>There is no exception here.<br>Please continue.<br>&gt;&gt;&gt;</pre><h4>With Statement</h4><p>The with statement is a guarded alternative to using <em>try-except-finally</em> statement. The with statement <em>test </em>should evaluate to an object that supports the contex manager protocol (having <em>__enter__()</em> and <em>__exit__()</em> methods). The syntax is given in EBNF below.</p><pre>with_stmt    := &quot;with&quot; with_item {&quot;,&quot; with_item} &quot;:&quot;<br>             := [TYPE_COMMENT] suite .<br>with_item    := test [&quot;as&quot; expr] .</pre><p>Given a text file <em>output.txt</em>, it can be opened for writing using</p><pre>&gt;&gt;&gt; f_obj = open(&quot;output.txt&quot;, &quot;w&quot;)<br>&gt;&gt;&gt;f_obj.write(&quot;Hello output&quot;)<br>12<br>&gt;&gt;&gt; f_obj.closed<br>False<br>&gt;&gt;&gt; f_obj.close()<br>&gt;&gt;&gt; f_obj.closed<br>True<br>&gt;&gt;&gt;</pre><p>A with statment can simplify it as shown below.</p><pre>&gt;&gt;&gt; with open(&quot;helloworld.txt&quot;, &quot;w&quot;) as file_obj:<br>...     file_obj.write(&quot;Hello world&quot;)<br>...<br>11<br>&gt;&gt;&gt; file_obj.closed<br>True<br>&gt;&gt;&gt;</pre><h4>Async Statement</h4><p>The “<em>async</em>” keyword can be used to make either a funcdef, with statement, for statment asynchronous.</p><p>Asynchronous functions are also called coroutines. They can be entered, exited and resumed at many different ponts. The <em>await</em> expression, <em>async for</em> and <em>async with</em> can only be used in coroutine function bodies.</p><p>This statement is denoted by the below syntax in EBNF.</p><pre>async_statment  := &quot;async&quot; (funcdef | with_stmt | for_stmt) .</pre><h3>Other Simple Statements</h3><h4>Expression Statement</h4><p>The so called expression statements perform different types of assignment. The syntax is shown below in EBNF.</p><pre>expr_stmt    := testlist_star_expr (annassign | <br>                augassign (yield_expr | testlist) |<br>                [&quot;=&quot; (yield_expr | testlist_star_expr)<br>                {&quot;=&quot; (yield_expr | testlist_star_expr)}<br>                [TYPE_COMMENT]]) .<br>annassign    := test [&quot;=&quot; (yield_expr | testlist_start_expr)] .<br>augassign    := &quot;+=&quot; | &quot;-=&quot; | &quot;*=&quot; | &quot;@=&quot; | &quot;/=&quot; | &quot;%=&quot; | &quot;&amp;=&quot; |<br>                &quot;|=&quot; | &quot;^=&quot; | &quot;&lt;&lt;=&quot; | &quot;&gt;&gt;=&quot; | &quot;**=&quot; | &quot;//=&quot; .</pre><p>Below are possible examples</p><pre>&gt;&gt;&gt; a = 2          # assign literal &#39;2&#39; to a <br>&gt;&gt;&gt; a += 3         # implies a = a + 3<br>&gt;&gt;&gt; a<br>5<br>&gt;&gt;&gt; a *= 5         # implies a = a * 5<br>&gt;&gt;&gt; a<br>25<br>&gt;&gt;&gt; a //= 3        # implies a = a // 3<br>&gt;&gt;&gt; a<br>8<br>&gt;&gt;&gt; </pre><h4>del Statements</h4><p>Deletions are performed using the “del” statement in python. Deletion of a name removes the binding of that name from the local or global namespace. If the name is unbound a NameError exception is raised.</p><p>Its syntax in EBNF is shown below.</p><pre>del_stmt     := &quot;del&quot; exprlist .<br></pre><p>For example</p><pre>&gt;&gt;&gt; a = 5<br>&gt;&gt;&gt; a<br>5<br>&gt;&gt;&gt; del a<br>&gt;&gt;&gt; a<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, &lt;module&gt;<br>NameError: name &#39;a&#39; is not defined<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; b = [1, 2, 3]<br>&gt;&gt;&gt; del b[1:]<br>&gt;&gt;&gt; b<br>[1]<br>&gt;&gt;&gt;</pre><p>Deletion of a slicing is equivalent to assignment of an empty slice.</p><h4>pass Statement</h4><p>The “pass” statment does nothing. Its syntax in EBNF is</p><pre>pass_stmt    := &quot;pass&quot; .</pre><p>It can be used as a place-holder to give a construct syntactic meaning without actually implementing anything. For example</p><pre>&gt;&gt;&gt; class M:<br>...     pass    # Remember to implement these.<br>...<br>&gt;&gt;&gt;</pre><h4>Flow Statements</h4><p>Flow statements are defined by the syntax below.</p><pre>flow_stmt     := break_stmt | continue_stmt | return_stmt |<br>                 raise_stmt | yield_stmt .<br>break_stmt    := &quot;break&quot; .<br>continue_stmt := &quot;continue&quot; .<br>return_stmt   := &quot;return&quot; [testlist_start_expr] .<br>raise_stmt    := &quot;raise&quot; [test [&quot;from&quot; test]] .<br>yield_stmt    := yield_expr .</pre><p>They are shown by the examples below</p><pre>&gt;&gt;&gt; # print out odd numbers.<br>&gt;&gt;&gt; i, n = 1, 20<br>&gt;&gt;&gt; while i &lt; n:<br>...     if i % 2 == 0:<br>...         i+=1<br>...         continue<br>...     print(i)<br>...     i+=1<br>...<br>1<br>3<br>5<br>7<br>9<br>11<br>13<br>15<br>17<br>19<br>&gt;&gt;&gt; # stop printing when you see an even number<br>&gt;&gt;&gt; i, n = 1, 20<br>&gt;&gt;&gt; while i &lt; n:<br>...     if i % 2 == 0:<br>...         break<br>...     print(i)<br>...     i+=1<br>...<br>1<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; raise<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>RuntimeError: No active exception to reraise<br>&gt;&gt;&gt;</pre><h4>assert Statement</h4><p>The assert statement is used for debugging purposes. Its syntax is expressed in EBNF below:</p><pre>assert_stmt   := &quot;assert&quot; test [&quot;,&quot; test] .</pre><p>Below is a simple example</p><pre>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; b = 3<br>&gt;&gt;&gt; assert a == b<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>AssertionError<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; assert a == 2<br>&gt;&gt;&gt;</pre><p>The assert statement is equivalent to</p><pre>if __debug__:<br>    if not test: raise AssertionError</pre><h4>global and nonlocal Statements</h4><p>The global statement treats the given identifiers as globals. If not defined prior to the statement, they are bound to the global namespace.</p><p>The nonlocal statement however, refers to previously bound variables in the nearest enclosing scope excluding globals.</p><p>There syntax are shown below in EBNF.</p><pre>global_stmt   := &quot;global&quot; identifier {&quot;,&quot; identifier} .<br>nonlocal_stmt := &quot;nonlocal&quot; identifier{&quot;,&quot; identifier} .</pre><p>For example</p><pre>&gt;&gt;&gt; #identifier &#39;a&#39; in function &#39;f&#39; is bound to global namespace<br>&gt;&gt;&gt; def f():<br>...     global a<br>...     a = 2<br>...<br>&gt;&gt;&gt; a<br>2<br>&gt;&gt;&gt; # Testing nonlocal variables<br>&gt;&gt;&gt; def f():<br>...     b = 2<br>...     def g():<br>...         nonlocal b<br>...         b = 3<br>...     print(b)<br>...     g()<br>...     print(b)<br>...<br>&gt;&gt;&gt; f()<br>2<br>3<br>&gt;&gt;&gt;</pre><h3>Tests</h3><p>Tests are defined by the syntax below in EBNF.</p><pre>testlist_comp      := (namedexpr_test | star_expr) <br>                      (comp_for | {&quot;,&quot; (namedexpr_test| star_expr}<br>                      [&quot;,&quot;] .<br>testlist_star_expr := (test | star_expr){&quot;,&quot;(test | start_expr)} <br>                       [&quot;,&quot;] .<br>testlist           := test {&quot;,&quot; test} [&quot;,&quot;] .<br>namedexpr_test     := test [&quot;:=&quot; test] .<br>test               := or_test [&quot;if&quot; or_test &quot;else&quot; test] | <br>                      lambdef .<br>test_nocond        := or_test | lambdef_nocond .<br>lambdef            := &quot;lambda&quot; [varargslist] &quot;:&quot; test .<br>lambdef_nocond     := &quot;lambda&quot; [varargslist] &quot;:&quot; test_nocond .<br>or_test            := and_test {&quot;or&quot; and_test } .<br>and_test           := not_test {&quot;and&quot; not_test } .<br>not_test           := &quot;not&quot; not_test | comparison .<br>comparison         := expr {comp_or expr} .<br>comp_op            := &quot;&lt;&quot; | &quot;&gt;&quot; | &quot;==&quot; | &quot;&gt;=&quot; | &quot;&lt;=&quot; | &quot;&lt;&gt;&quot; |<br>                      &quot;!=&quot; | &quot;in&quot; | &quot;not&quot; &quot;in&quot; | &quot;is&quot; |&quot;is&quot; &quot;not&quot; .<br>comp_iter          := comp_for | comp_if .<br>sync_comp_for      := &quot;for&quot; exprlist &quot;in&quot; or_test [comp_iter] .<br>comp_for           := &quot;async&quot; sync_comp_for .<br>comp_if            := &quot;if&quot; test_nocond [comp_iter] .</pre><p>Examples include</p><pre>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; b = 3<br>&gt;&gt;&gt; a and b              # not test<br>3<br>&gt;&gt;&gt; a or b               # or_test<br>2<br>&gt;&gt;&gt; not a<br>False<br>&gt;&gt;&gt; d = [4, 3, 2]<br>&gt;&gt;&gt; a not in d           # comparison test<br>False<br>&gt;&gt;&gt; a is not b<br>True<br>&gt;&gt;&gt; a = None<br>&gt;&gt;&gt; a or b<br>3<br>&gt;&gt;&gt; a = 4<br>&gt;&gt;&gt; a in d<br>True<br>&gt;&gt;&gt; a in b<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>TypeError: argument of type &#39;int&#39; is not iterable<br>&gt;&gt;&gt;</pre><h3>Expressions</h3><p>Expressions are used to denote rules of computations. The below syntax in EBNF describes them.</p><pre>exprlist       := (expr | star_expr){&quot;,&quot; (expr | star_expr)}[&quot;,&quot;] .<br>start_expr     := &quot;*&quot; expr .<br>expr           := xor_expr {&quot;|&quot; xor_expr} .<br>xor_expr       := and_expr {&quot;^&quot; and_expr} .<br>and_expr       := shift_expr {&quot;&amp;&quot; shift_expr} .<br>shift_expr     := arith_expr {(&quot;&lt;&lt;&quot; | &quot;&gt;&gt;&quot;) arith_expr} .<br>arith_expr     := term {(&quot;+&quot; | &quot;-&quot;) term} .<br>term           := factor {(&quot;*&quot; | &quot;@&quot; | &quot;/&quot; | &quot;%&quot; | &quot;//&quot;) factor } .<br>factor         := (&quot;+&quot; | &quot;-&quot; | &quot;~&quot;) factor | power .<br>power          := atom_expr [&quot;**&quot; factor] .<br>atom_expr      := [&quot;await&quot;] atom {trailer} .<br>atom           := (&quot;(&quot; [yield_expr | testlist_comp] &quot;)&quot; |<br>                  &quot;[&quot; [testlist_comp] &quot;]&quot; | &quot;{&quot;[dictorsetmaker] &quot;}&quot;<br>                  | identifier | number | string{string} |<br>                  &quot;...&quot; | &quot;None&quot; | &quot;True&quot; | &quot;False&quot; .<br>trailer        := &quot;(&quot; [arglist] &quot;)&quot; | &quot;[&quot; subscriptlist &quot;]&quot; | <br>                  &quot;.&quot; identifier .<br>subscriptlist  := subscript {&quot;,&quot; subscript} [&quot;,&quot;] .<br>subscript:     := test | [test] &quot;:&quot; [test] [sliceop] .<br>sliceop        := [test] .<br>dictorsetmaker := ((test &quot;:&quot; test | &quot;**&quot; expr) (comp_for |<br>                  {&quot;,&quot; (test &quot;:&quot; test | &quot;**&quot; expr)} [&quot;,&quot;])) |<br>                  (test|star_expr) (comp_for | <br>                  {&quot;,&quot; (test|star_expr)} [&quot;,&quot;])) .<br>yield_expr     := &quot;yield&quot; [yield_arg] .<br>yield_arg      := &quot;from&quot; test | testlist_star_expr .</pre><p>Examples are given below</p><pre>&gt;&gt;&gt; 5 % 2         # Give me remainder<br>1<br>&gt;&gt;&gt; 5 // 2        # Given me integer quotient<br>2<br>&gt;&gt;&gt; 5 ** 2<br>25<br>&gt;&gt;&gt; [5, 3, 2]<br>[5, 3, 2]<br>&gt;&gt;&gt; 5 / 2<br>2.5<br>&gt;&gt;&gt; 5 * 2 + 3<br>13<br>&gt;&gt;&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f7c2f54c0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/python-syntax-semantics-and-standard-library-syntactic-convention-f0f7c2f54c0b">Python: Syntax, Semantics and Standard Library — Syntactic Convention</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Syntax, Semantics and Standard Library]]></title>
            <link>https://medium.com/django-framework-real-world-projects/python-syntax-semantics-and-standard-library-f3dbee7a5078?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/f3dbee7a5078</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 16:37:53 GMT</pubDate>
            <atom:updated>2020-04-21T22:36:22.911Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>updated</strong> for <strong>python 3.8.2</strong></p><p><em>Python experts perform more magic than the witches of Salem, you only have to check the source of django to agree with me.</em></p><p><em>I possess in my arsenal, a firewall more potent than what president Xi commands, with it I filter out intellectual excellence from chaff. Simply put, if I engage your project, you are an expert of your craft.</em></p><p><em>Easy problems are only good for giving you false hopes and wasting your time. Better a month working on a hard problem than a day working on 30 easy problems.</em></p><p><em>I am never satisfied with my understanding of a mathematical formalism till I touch its grammar.</em></p><h3>Table of Content</h3><p>This write-up is broken down into three parts.</p><ol><li>Part 1 — Lexical Convention (This is what you are reading now)</li><li>Part 2 — Syntactic Convention</li><li>Part 3 — Standard Library</li></ol><p>While Part 1 and 2 contain little examples, the real fun is at Part 3. There I built a small web framework called <em>SimpleDjango, </em>a simple version of django. I also incorporated the ability to build REST and GraphQL apis with it which are based on Django Rest Framework and Ariadne respectively.</p><h3>Quick Write-Up</h3><p>The <a href="https://docs.python.org/3/"><em>Official python documentation</em></a> remains the best source of authentic information on python. What is presented here is a condensed form of it.</p><p>Whereas a craftsman needs a complete understanding of his tools, his experience is rated by the problems he has solved or he can solve.</p><h3><strong>Without Further Ado</strong></h3><p>At a fundamental level, a, programming language is an infinite set of finite sequences of symbols from a <em>symbol set</em>. Each symbol is a sequence of finite characters from a <em>character set</em>.</p><p>Each finite sequence of symbols can be called a sentence or the python program. Each sentence must be well-formed according to the syntax of the language else a <em>SyntaxError</em> occurs. To describe the syntax, we use the EBNF by Professor <a href="https://inf.ethz.ch/personal/wirth/"><em>Niklaus Wirth</em></a>.</p><p>Consider a simple example below, an expression involving two numbers and an operator.</p><pre>&gt;&gt;&gt; 2+2</pre><p>In terms of tokens what we wrote above is</p><pre>==&gt; &lt;literal&gt; &lt;operator&gt; &lt;literal&gt;<br>==&gt; &lt;digit&gt; &lt;&quot;+&quot;&gt; &lt;digit&gt;<br>==&gt; &lt;&quot;2&quot;&gt; &lt;&quot;+&quot;&gt; &lt;&quot;2&quot;&gt;</pre><p>The python interpreter can be invoked in interactive mode. It reads and executes one statement at a time. Using the EBNF syntax, we have:</p><pre>single_input := NEWLINE | simple_stmt | <br>                compound_stmt NEWLINE  .</pre><p>The interactive shell can be considered to be a module. Every module has a name denoted by the identifier <em>__name__</em>. A module can also have a docstring denoted by the identifier <em>__doc__</em>.</p><pre>C:\&gt;python<br>Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>&gt;&gt;&gt; __name__         # Python, what is identifier &#39;__name__&#39; ?<br>&#39;__main__&#39;<br>&gt;&gt;&gt; type(__name__)   # What is &#39;type(__name__)&#39; ?<br>&lt;class &#39;str&#39;&gt;</pre><h3>Lexical Convention</h3><p>A scanner or lexical analyzer reads the given character sequence from its character set and forms symbols or tokens.</p><h4>Character set</h4><p>The Unicode character set is used. The default encoding however is UTF-8. A different encoding can be specified using an <em>encoding declaration</em>.</p><h4>Symbol set</h4><p>The symbol set of python consists of NEWLINE, DEDENT, INDENT, identifiers, literals, operators, delimiters and comments.</p><pre>symbol_set := NEWLINE |INDENT | DEDENT | comment |<br>              literal | identifier | operator | delimiters .</pre><p><strong><em>NEWLINE:</em></strong> A well-formed python sentence can be considered to be divided into a number of logical lines. The NEWLINE token represents its end. Two or more physical lines can be joined into a logical line using the backslash character \.</p><p><strong><em>INDENT &amp; DEDENT</em></strong>: Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line. The indentation levels of consecutive lines are used to generate <em>INDENT</em> and <em>DEDENT</em> tokens using a stack.</p><p><strong><em>comment:</em></strong> A comment starts with ta # character that is not part of a string literal and extends to the end of the physical line. They exists to clarify code.</p><h4><strong>literal</strong></h4><p>Python has support for numeric literals used in computation and also string literals used for text processing.</p><pre>literal           := numeric_literals | string_literals .<br>numeric_literals  := integer | floatnumber | imagnumber .<br>string_literals   := string_literal | bytes_literal |<br>                     formatted_string_literal .</pre><p><strong>Numeric literals</strong></p><p>Numeric literals include integers, floating point numbers and imaginary numbers. A complex numbers can be formed by adding real number number to an imaginary number. This is shown below.</p><p><strong>integer literals</strong></p><p>Integers in python can be represented in decimal, binary, octal and hexadecimal forms. This is shown below</p><pre>integer     := decinteger | bininteger | octinteger |<br>               hexinteger .<br>decinteger  := nonzerodigit {[&quot;_&quot;] digit} | <br>               &quot;0&quot;{&quot;0&quot;} {[&quot;_&quot;] &quot;0&quot;} .<br>bininteger  := &quot;0&quot; (&quot;b&quot; | &quot;B&quot;) [&quot;_&quot;] bindigit {[&quot;_&quot;] bindigit} .<br>octinteger  := &quot;0&quot; (&quot;o&quot; | &quot;O&quot;) [&quot;_&quot;] octdigit {[&quot;_&quot;] octdigit} .<br>hexinteger  := &quot;0&quot; (&quot;x&quot; | &quot;X&quot;) [&quot;_&quot;] hexdigit {[&quot;_&quot;] hexdigit} .<br>nonzerodigit:= &quot;1&quot; ... &quot;9&quot; .<br>bindigit    := &quot;0&quot; | &quot;1&quot; .<br>octdigit    := &quot;0&quot; ... &quot;7&quot; .<br>hexdigit    := digit | &quot;a&quot; ... &quot;f&quot; | &quot;A&quot; ... &quot;F&quot; .<br>digit       := &quot;0&quot; ... &quot;9&quot; .</pre><p>Accepted integers include:</p><p>binary -&gt; 0b101, 0B101, 0b_1010_1111, 0B_1010_1111 etc</p><p>octal -&gt; 0o01, 0O10, 0o_237_413 etc</p><p>hex -&gt; 0x01, 0X01, 0x_1101_2349, 0xf etc</p><p>dec -&gt; 12, 3435, 1_023_212 etc</p><p>Invalid integers include:</p><p>dec -&gt; 012, 0_23 etc</p><p>hex -&gt; 0xg etc</p><p>oct -&gt; 0o9, 0O8 etc</p><p>bin -&gt; 0b2, 0B3 etc</p><p>Let us play a bit in the interactive mode.</p><pre>&gt;&gt;&gt; 3<br>3<br>&gt;&gt;&gt; type(3)          # what is &#39;type(3)&#39;<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt;&gt; type(0b01_11)    # what is &#39;type(0b01_11)<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt; 0b01_11           # what is &#39;0b01_11&#39;</pre><p><strong>floating point literals</strong></p><p>Floating point numbers are defined using the below syntax in EBNF.</p><pre>floatnumber   := pointfloat | exponentfloat .<br>pointfloat    := [digitpart] fraction | digitpart &quot;.&quot; .<br>exponentfloat := (digitpart | pointfloat) exponent .<br>fraction      := &quot;.&quot; digitpart .<br>exponent      := (&quot;e&quot; | &quot;E&quot;) [&quot;+&quot; | &quot;-&quot;] digitpart .<br>digitpart     := digit {[&quot;_&quot;] digit} .</pre><p>Accept floating point numbers include:</p><p>pointfloat -&gt; 4.31, 4. , 0.103, 0.00003, .1, .013, 12_31.23_4, etc</p><p>exponentfloat -&gt; 3.14e+5, 4e+5, 4E+5 etc</p><p>We mess a bit in the interactive mode.</p><pre>&gt;&gt;&gt; 4.31<br>4.31<br>&gt;&gt;&gt; type(4.31)        # what is &#39;type(4.31)&#39; ?<br>&lt;class &#39;float&#39;&gt;<br>&gt;&gt;&gt; 3.143E+5<br>314300.0<br>&gt;&gt;&gt; 3.143e-2<br>0.03143</pre><p><strong>imaginary literals</strong></p><p>Imaginary literal yields a complex number with a real part of 0.0. To create a complex number with a non-zero real part add a floating point number to the <em>imagnumber</em>. This is described by the below syntax in EBNF.</p><pre>imagnumber   := (floatnumber | digitpart) (&quot;j&quot; | &quot;J&quot;) .</pre><p>Accepted imaginary numbers include:</p><p>4.31j, 4+5j, 4.3+6j etc</p><pre>&gt;&gt;&gt; 4.31j<br>4.31j<br>&gt;&gt;&gt; type(4.31j)       # what is &#39;type(4.31j)&#39; ?<br>&lt;class &#39;complex&#39;&gt;<br>&gt;&gt;&gt; 4.3+6j<br>(4.3+6j)<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(4.3+6j)      # what is &#39;type(4.3+6j)&#39; ?<br>&lt;class &#39;complex&#39;&gt;</pre><p><strong>String Literals</strong></p><p>Python supports the string literals and bytes literals. Literals which are prefix by “f” or “F” qualify for the formatted string literals.</p><pre>string_literals := stringliteral | bytesliteral .</pre><p><strong>stringliteral and bytesliteral</strong></p><p>Here we discuss strings of the form (“…”), (‘…’), (“””….”””), (‘’’…’’’). This strings also accept certain prefixes which are defined in the syntax below.</p><pre>stringliteral   := [stringprefix](shortstring | longstring) .<br>stringprefix    := &quot;r&quot; | &quot;u&quot; | &quot;R&quot; | &quot;U&quot; | &quot;f&quot; | &quot;F&quot; |<br>                   &quot;fr&quot; | &quot;Fr&quot; | &quot;fR&quot; | &quot;FR&quot; | &quot;rf&quot; | <br>                   &quot;Rf&quot; | &quot;RF&quot; .<br>shortstring     := &quot;&#39;&quot; {shortstringitem} &quot;&#39;&quot; | <br>                   &#39;&quot;&#39; {shortstringitem} &#39;&quot;&#39; .<br>longstring      := &quot;&#39;&#39;&#39;&quot; {longstringitem} &quot;&#39;&#39;&#39;&quot; |<br>                   &#39;&quot;&quot;&quot;&#39; {longstringitem} &#39;&quot;&quot;&quot;&#39; .<br>shortstringitem := shortstringchar | stringescapeseq .<br>longstringitem  := longstringchar | stringescapeseq .<br>shortstringchar := &lt;any source character except &quot;\&quot; or<br>                   newline or the quote&gt; .<br>longstringchar  := &lt;any source character except &quot;\&quot;&gt; .<br>stringescapeseq := &quot;\&quot; &lt;any source character&gt; .</pre><p>Bytes literal unlike string literals accept only ASCII characters.</p><pre>bytesliteral    := bytesprefix(shortbytes | longbytes ) .<br>bytesprefix     := &quot;b&quot; | &quot;B&quot; | &quot;br&quot; | &quot;Br&quot; | &quot;bR&quot; | &quot;BR&quot; |<br>                   &quot;rb&quot; | &quot;rB&quot; | &quot;Rb&quot; | &quot;RB&quot; .<br>shortbytes      := &quot;&#39;&quot; {shortbytesitem} &quot;&#39;&quot; |<br>                   &#39;&quot;&#39; {shortbytesitem} &#39;&quot;&#39; .<br>longbytes       := &quot;&#39;&#39;&#39;&quot; {longbytesitem} &quot;&#39;&#39;&#39;&quot; |<br>                   &#39;&quot;&quot;&quot;&#39; {longbytesitem} &#39;&quot;&quot;&quot;&#39; .<br>shortbytesitem  := shortbyteschar | bytesescapeseq .<br>longbytesitem   := longbyteschar  | bytesescapeseq .<br>shortbyteschar  := &lt;any ASCII character except &quot;\&quot;<br>                   or newline or the quote&gt; .<br>longbyteschar   := &lt;any ASCII character except &quot;\&quot;&gt; .<br>bytesescapeseq  := &quot;\&quot; &lt;any ASCII character&gt; .</pre><p>Valid stringliterals and bytesliterals include:</p><pre>&gt;&gt;&gt; &#39;test identifier&#39;<br>&#39;test identifier&#39;<br>&gt;&gt;&gt; &quot;test identifier&quot;<br>&quot;test identifier&quot;<br>&gt;&gt;&gt; &quot;I don&#39;t know.&quot;<br>&quot;I don&#39;t know.&quot;<br>&gt;&gt;&gt; &quot;&quot;&quot;I am also an identifier.&quot;&quot;&quot;<br>&#39;I am also an identifier.&#39;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; b&quot;Obi is a boy&quot;<br>b&#39;Obi is a boy&#39;<br>&gt;&gt;&gt; print(&quot;C:\a\name&quot;)<br>C:<br>ame<br>&gt;&gt;&gt; print(r&quot;C:\a\name&quot;)   # Use &#39;r&#39; prefix to print escapes<br>C:\a\name</pre><p>Python has escape sequences for non-printable characters, the backlash, writing there octal and hex values. The below works for string and bytes literals.</p><pre>Escape Sequence    |  Meaning<br>-----------------------------<br>\newline            Backslash and newline ignored<br>\\                  Backslash (\)<br>\&#39;                  Single quote (&#39;)<br>\&quot;                  Double quote (&quot;)<br>\a                  ASCII Bell (BEL)<br>\b                  ASCII Backspace (BS)<br>\f                  ASCII Formfeed (FF)<br>\n                  ASCII Linefeed (LF)<br>\r                  ASCII Carriage Return (CR)<br>\t                  ASCII Horizontal Tab (TAB)<br>\v                  ASCII Vertical Tab (VT)<br>\ooo                Character with octal value ooo<br>\xhh                Character with hex value hh</pre><p>The below escape sequences only work for string literals.</p><pre>Escape Seqence        |  Meaning<br>---------------------------------<br>\N{name}               Character named name in Unicode<br>\uxxxx                 Character with 16-bit hex value xxxx<br>\Uxxxxxxxx             Character with 32-bit hex value</pre><p>String literals prefixed by “f” or “F” are called formatted string literals, the below syntax in EBNF defines them.</p><pre>f_string          := {literal_char | &quot;{{&quot; | &quot;}}&quot; |<br>                     replacement_field} .<br>replacement_field := &quot;{&quot; f_expression [&quot;!&quot; conversion] <br>                     [&quot;:&quot; format_spec] &quot;}&quot; .<br>f_expression      := (condition_expression | &quot;*&quot; or_expr) <br>                     {&quot;,&quot; conditional_expression |<br>                     &quot;,&quot; &quot;*&quot; or_expr} [&quot;,&quot;] | <br>                     yield_expression .<br>conversion        := &quot;s&quot; | &quot;r&quot; | &quot;a&quot; .<br>format_spec       := {literal_char | NULL | <br>                     replacement_field } .<br>literal_char      := &lt;any Unicode character except &quot;{&quot;<br>                     &quot;}&quot; or NULL&gt; .</pre><p>Examples include:</p><pre>&gt;&gt;&gt; name = &quot;Obi&quot;<br>&gt;&gt;&gt; f&quot;My name is {name!r}.&quot;<br>&quot;My name is &#39;Obi&#39;.&quot;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; name = &quot;London City&quot;<br>&gt;&gt;&gt; f&quot;I am going to the big {name!r}.&quot;<br>&quot;I am going to the big &#39;London City&#39;.&quot;</pre><h4>identifier</h4><p>In the beginning, our identifiers only used ASCII characters. We could define it as:</p><pre>identifier := (letter | &quot;_&quot;) {&quot;_&quot; | digit | letter} .<br>letter     := &quot;A&quot; ... &quot;Z&quot; | &quot;a&quot; ... &quot;z&quot; .<br>digit      := &quot;0&quot; ... &quot;9&quot; .</pre><p>Then the Chinese complained, the Russians complained, the Koreans complained, the Israelis complained. In fact, everybody was complaining. As a result, Unicode charset was born. With it came the problem of encodings; UTF-8, UTF-16BE, UTF-16LE etc. Well python uses Unicode for identifiers, string literals and comments now. The standard library still uses ASCII characters for identifiers (thanks python).</p><p>Python uses the Unicode standard annex UAX-31 to describe the syntax of identifiers. The ASCII range 0X00–0X7F is same as the U+0000 — U+007F of the Unicode charset. So we can still reason in terms of good old ASCII.</p><p>Check out <a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers">Python doc</a>, <a href="https://www.python.org/dev/peps/pep-3131/">PEP 3131</a> for more information on the syntax used to describe identifiers.</p><p><strong>keywords</strong></p><p>Python also have identifiers that have special meaning and are used as reserved words. They cannot be used as ordinary identifiers. They include:</p><pre>and      class      except    import     or      with<br>as       continue   finally   in         pass    yield<br>assert   def        for       is         raise<br>async    del        from      lambda     return<br>await    elif       global    nonlocal   try<br>break    else       if        not        while</pre><p>Asides from keywords, there are identifiers that have special meaning.</p><p>Identifiers that begin with the underscore “_ “ are not imported by the <em>import statement</em>. In the interactive mode, it also denotes the result of the last evaluation.</p><p>Identifiers of the form “__*__” are system-defined names. They have special meaning to the python interpreter.</p><p>Identifiers that begin with double underscore “__” are private identifiers in <em>class statements</em>.</p><p>There are other identifiers though not tokens, but have certain meaning and functions in the system. They are described below.</p><p><strong>The concept of identifiers.</strong></p><p>Most modern programming languages are algebraic languages. Identifiers are used to denote variable, built-types, functions, user-defined types.</p><pre>&gt;&gt;&gt; int         #Python, what is int ?<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(int)   #Python, what is &#39;type(int)&#39; ?<br>&lt;class &#39;type&#39;&gt;<br>&gt;&gt;&gt; float       #Python, what is &#39;float&#39; ?<br>&lt;class &#39;float&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; def a():<br>...     pass<br>...<br>&gt;&gt;&gt; a           #Python, what is &#39;a&#39; ?<br>&lt;function a at 0x02537808&gt;<br>&gt;&gt;&gt; type(a) <br>&lt;class &#39;function&#39;&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; dir         #Python, what is &#39;dir&#39; ?<br>&lt;built-in function dir&gt;<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; type(dir)   #Python, what is &#39;type(dir)&#39; ?<br>&lt;class &#39;builtin_function_or_method&#39;&gt;</pre><p><strong>built-in functions</strong></p><p>The standard library provides identifiers that denote built-in function objects. These identifiers can be assigned to. The are listed below:</p><pre>abs          enumerate   input        ord      zip<br>all          eval        isinstance   pow      __import__<br>any          exec        issubclass   print<br>ascii        filter      iter         repr<br>bin          format      len          reversed<br>breakpoint   getattr     locals       round<br>callable     globals     map          setattr<br>chr          hasattr     max          slice<br>compile      hash        min          sorted<br>delattr      help        next         sum<br>dir          hex         oct          super<br>divmod       id          open         vars</pre><p><strong>built-in types</strong></p><p>The standard library provides identifiers that denote built-in types. These identifiers can be assigned to. They are listed below.</p><pre>bool          dict        memoryview   staticmethod<br>bytearray     float       object       str<br>bytes         frozenset   property     tuple<br>classmethod   int         range        type<br>complex       list        set</pre><p><strong>built-in exceptions</strong></p><p>The standard library provides identifiers that denote exceptions. They can be assigned to. They are listed below</p><pre> BASE CLASSES<br>-------------</pre><pre>BaseException    ArithmeticError   <br>Exception        BufferError<br>LookupError</pre><pre>CONCRETE EXCEPTIONS<br>-------------------<br>AssertionError       MemoryError         SyntaxError<br>AttributeError       NameError           IndentationError<br>EOFError             NotImplementedError TabError    <br>FloatingPointError   OsError             SystemError<br>GeneratorExit        OverflowError       SystemExit<br>ImportError          RecursionError      TypeError<br>ModuleNotFoundError  ReferenceError      UnboundLocalError<br>IndexError           RuntimeError        UnicodeEror<br>KeyError             StopIteration       UnicodeEncodeError<br>KeyboardInterrupt   StopAsyncIteration  UnicodeTranslateError<br>ValueError           ZeroDivisionError   EnvironmentError<br>IOError              WindowsError</pre><pre>OS EXCEPTIONS<br>-------------<br>BlockingIOError          FileNotFoundError<br>ChildProcessError        InterruptedError<br>ConnectionError          IsADirectoryError<br>BrokenPipeError          NotADirectoryError<br>ConnectionAbortedError   PermissionError<br>ConnectionRefusedError   ProcessLookupError<br>ConnectionResetError     TimeoutError<br>FileExistsError</pre><pre>WARNINGS<br>---------<br>Warning                     FutureWarning<br>UserWarning                 ImportWarning<br>DeprecationWarning          UnicodeWarning<br>PendingDeprecationWarning   BytesWarning<br>SyntaxWarning               ResourceWarning<br>RuntimeWarning</pre><p>Exceptions have are certain hierarchy which can be viewed at <a href="https://docs.python.org/3/library/exceptions.html#exception-hierarchy">exception hierarchy</a>.</p><p><strong>built-in constants</strong></p><p>The standard library provides identifiers that denote constants. These identifiers cannot be assigned to except for <em>Ellipsis </em>and<em> NotImplemented</em>. They are listed below .</p><pre>False     NotImplemented<br>True      Ellipsis<br>None      __debug__</pre><p><strong>site constants</strong></p><p>There are identifiers added by <a href="https://docs.python.org/3/library/site.html#module-site">site</a>(Site-specific configuration hook). Thought these identifiers can be assigned to, they should not, for then they loose there special meaning.</p><pre>quit     exit     copyright   credits   license</pre><p><strong>built-in modules</strong></p><p>The identifier <em>__builtins__</em> denotes the builtins module. DO NOT assign to it, or your built-identifiers malfunctions.</p><h4><strong>operator</strong></h4><p>The below characters serve as operators in python.</p><pre>+   -    *    **   //    /   @<br>%   &lt;&lt;   &lt;    &gt;    &gt;&gt;    &amp;   |<br>^   ~    :=   &lt;=   ==    !=  &lt;=</pre><h4>delimiter</h4><p>The below characters serve as delimiters in python.</p><pre>(     )    [      ]    {     }<br>,     :    .      ;    @     =<br>-&gt;    +=   -=     *=   /=    //=<br>%=    @=   &amp;=     |=   ^=    &gt;&gt;=<br>&lt;&lt;=   **=  &#39;      &quot;    #     \</pre><p>Also sequence of three periods has a special meaning as an ellipsis</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3dbee7a5078" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/python-syntax-semantics-and-standard-library-f3dbee7a5078">Python: Syntax, Semantics and Standard Library</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python, The 4 Horsemen and End of Days Prophecy.]]></title>
            <link>https://medium.com/django-framework-real-world-projects/python-the-4-horsemen-and-end-of-days-prophecy-3632b12f1377?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/3632b12f1377</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Tue, 17 Mar 2020 10:38:49 GMT</pubDate>
            <atom:updated>2020-03-21T10:35:50.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Django is Python and Python is more than Django</em>.</p><p><em>Web development is difficult. Whomever says otherwise is a liar</em>.</p><p>If you are an adherent of any of the Abrahamic religions, you may have read about the Four Horsemen of the Apocalypse from the Book of Revelations (scary…. yikes). Perhaps you learn’t about them from Wikipedia or even the X-factor published by Marvels comics. In all cases they stand for terrible things.</p><p>Well I bring to you a new kind of Horsemen (I swear they are not destructive, and certainly won’t bring the world to an end… promise) in the form of four web problems, namely: <strong><em>the server-side web framework problem</em></strong>, <strong>the content management system problem</strong>, <strong><em>the ecommerce problem</em></strong> and <strong><em>the web API design problem</em></strong>.</p><p>Algorithmic reasoning of these problems is expressed using the python formalism, hence a thorough understanding of the syntactic and semantic requirements of python is required. This gives rise to <strong><em>Python: Syntax, Semantics and Standard Library</em></strong>.</p><p>For the server-side web framework problem, we study the Django web framework, this gives birth to <strong><em>Rebuilding Django</em></strong>.</p><p>To properly understand the content management system problem, we closely study <a href="http://mezzanine.jupo.org/"><em>Mezzanine CMS project</em></a>, and the <a href="https://wagtail.io/">Wagtail CMS project</a>. This gives rise to two additional projects, namely: <strong><em>Rebuilding Mezzanine CMS</em></strong> and <strong><em>Rebuilding Wagtail CMS.</em></strong></p><p>To properly understand <em>the ecommerce problem</em>, we closely study the <a href="http://oscarcommerce.com/">Django Oscar project</a> and its minions. We also closely study the <a href="http://cartridge.jupo.org/">Cartridge project</a> and the <a href="https://saleor.io/">Saleor project</a>. This gives rise to <strong><em>Rebuilding Django Oscar and it Minions, Rebuilding Cartridge </em></strong>and finally <strong><em>Rebuilding Saleor</em></strong>.</p><p>To properly understand web API design, we closely study the <a href="https://www.django-rest-framework.org/">Django RestFramework</a> for REST based APIs, and <a href="https://ariadnegraphql.org/">Ariadne</a> for graphql based APIs. This gives rise to <strong><em>Rebuilding Django REST Framework </em></strong>and <strong><em>Rebuilding Ariadne.</em></strong></p><p>Also as a bonus, for a thorough understanding of authentication, we study the <a href="https://django-allauth.readthedocs.io/en/latest/installation.html">django-allauth </a>project which results in <strong><em>Rebuilding django-allauth</em></strong>.</p><p><strong>The four problems are explained in details at</strong></p><ol><li>The server-side web framework problem</li><li>The content management system problem</li><li>The ecommerce problem</li><li>The web API design problem</li></ol><p><strong>Projects Table of Content</strong></p><ol><li>Python: Syntax, Semantics and Standard Library.</li><li>Rebuilding Django.</li><li>Rebuilding Django REST framework.</li><li>Rebuilding Ariadne.</li><li>Rebuilding Django Oscar and its Minions.</li><li>Rebuilding Mezzanine.</li><li>Rebuilding Wagtail.</li><li>Rebuilding Cartridge.</li><li>Rebuilding Saleor.</li><li>Rebuilding Django Allauth</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3632b12f1377" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/python-the-4-horsemen-and-end-of-days-prophecy-3632b12f1377">Python, The 4 Horsemen and End of Days Prophecy.</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A First Project — A Simple CMS : Part 2]]></title>
            <link>https://medium.com/django-framework-real-world-projects/a-first-project-a-simple-cms-part-2-9916e593ba71?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/9916e593ba71</guid>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 12:00:58 GMT</pubDate>
            <atom:updated>2019-12-02T17:15:32.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>A First Project — A Simple CMS : Part 2</h3><p>updated for python <strong>3.8.0</strong> and django <strong>2.2.7</strong></p><p>We continue from <a href="https://medium.com/django-framework-real-world-projects/first-project-a-simple-cms-78e53f7bebff">Part 1</a>.</p><p><strong>First things first:</strong></p><p>We create a new app called <em>cms</em> and also a <em>urls.py</em> file in it.</p><p>We create the app with the command:</p><pre>python manage.py startapp cms</pre><p>add it to our<strong><em> simplecms/settings.py</em></strong> file as shown</p><pre>INSTALLED_APPS = [<br>  &#39;django.contrib.admin&#39;,<br>  ...</pre><pre>  &#39;cms.apps.CmsConfig&#39;,  #new<br>]</pre><p>Our directory structure should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*xTCT6TDNmmd8-xbYFrD8Bw.png" /><figcaption>current direct structure</figcaption></figure><p><strong>cms/urls.py</strong></p><p>Add the following code to it</p><pre>from django.urls import path</pre><pre>from django.shortcuts import render</pre><pre>app_name = &#39;cms&#39;</pre><pre>urlpatterns = [<br>  path(&#39;&#39;, lambda request: render(request, &#39;cms/home.html&#39;),<br>    name=&#39;home&#39;),<br>]</pre><p><strong>simplecms/urls.py</strong></p><p>Remove the from <strong><em>django.shortcuts import render</em></strong> and also update the <strong><em>‘ ‘</em></strong> path to redirect to the cms url. Import <strong><em>include</em></strong> as shown below.</p><pre>...<br>from django.contrib import admin<br>from django.urls import path, include   #new</pre><pre>urlpatterns = [<br>  ...<br>  path(&#39;&#39;, include(&#39;cms.urls&#39;)),</pre><p>Create a directory <em>cms</em> inside the <em>templates</em> directory and move <em>home.html</em> to it. Create a <em>base.html</em> file in the root <em>templates</em> directory. You template directory should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*raOXQAbGpJusDkC6CLa9gw.png" /><figcaption>current templates dir structure</figcaption></figure><p><strong>templates/base.html</strong></p><p>Add the below boilerplate code:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;title&gt;{% block title %}{% endblock %} - {{site_title}}&lt;/title&gt;</pre><pre>&lt;/head&gt;</pre><pre>&lt;body&gt;</pre><pre>  &lt;header&gt;<br>    &lt;div class=&quot;site-header&quot;&gt;</pre><pre>      &lt;div class=&quot;site-info&quot;&gt;<br>      &lt;a class=&quot;site-title&quot; href=&quot;{{home_url}}&quot;&gt;{{site_title}}&lt;/a&gt;<br>      &lt;p class=&quot;site-tagline&quot;&gt;{{site_tagline}}&lt;/p&gt;<br>      &lt;/div&gt;</pre><pre>    &lt;/div&gt;<br>  &lt;/header&gt;<br>  <br>  {% block content %}{% endblock %}</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>templates/cms/home.html</strong></p><p>Replace the code in <em>home.html</em> with the below:</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% block title %}Home{% endblock %}</pre><pre>{% block content %}&lt;h2&gt;Welcome to SimpleCMS &lt;/h2&gt;{% endblock %}</pre><p>Create a file <em>context_processors.py</em> inside the <em>cms</em> app directory.</p><p><strong>cms/context_processors.py</strong></p><p>Add the below code.</p><pre>from django.conf import settings</pre><pre>def sitedata(request):<br>  return {<br>    &#39;site_title&#39;: settings.CMS_SITE_TITLE,<br>    &#39;site_tagline&#39;: settings.CMS_SITE_TAGLINE,<br>    &#39;home_url&#39;: settings.CMS_HOME_URL,<br>  }</pre><p><strong>simplecms/settings.py</strong></p><p>Update your <em>settings.py</em> file with the below code</p><pre>...<br>CMS_SITE_TITLE = &#39;SimpleCMS&#39;<br>CMS_SITE_TAGLINE = &#39;A simple django CMS&#39;</pre><pre>from django.urls import reverse_lazy<br>CMS_HOME_URL = reverse_lazy(&#39;cms:home&#39;)</pre><p>Then add <strong><em>cms.context_processors.sitedata</em></strong> to <strong><em>context_processors</em></strong> in <strong><em>TEMPLATES</em></strong> located in <strong><em>simplecms/settings.py</em></strong> file.</p><p>Now if you run the server with <strong><em>python manage.py runserver</em></strong>, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*znX-FPboQ1QSf_9bWlRe9A.png" /><figcaption>snapshot of the work so far</figcaption></figure><p>Lets jump to models, very simple ones if I may add.</p><p><strong>cms/models.py</strong></p><p>We are going to create a category model that has just a title, slug and optional description. A post model that has a title, slug, content, date_created, date_updated, status, and that relates to a user, a category.</p><p>These are shown below:</p><pre>...<br>from django.contrib.auth import get_user_model</pre><pre>from django.urls import reverse</pre><pre>User = get_user_model()</pre><pre>class Category(models.Model):<br>  title = models.CharField(max_length=100)<br>  slug = models.SlugField(unique=True)<br>  description = models.TextField()</pre><pre>  class Meta:<br>    ordering = [&#39;title&#39;]<br>    verbose_name_plural = &#39;Categories&#39;</pre><pre>  def __str__(self):<br>    return self.title</pre><pre>  def get_absolute_url(https://medium.com/self):<br>    return reverse(&#39;cms:category_posts&#39;, kwargs={<br>      &#39;slug&#39;: self.slug})</pre><pre>class Post(models.Model):</pre><pre>  DRAFT, PUBLISHED = 0, 1<br>  STATUS_CHOICES = (<br>    (DRAFT, &#39;Draft&#39;),<br>    (PUBLISHED, &#39;Published&#39;),<br>  )</pre><pre>  title = models.CharField(max_length=200)<br>  slug = models.SlugField(unique=True)<br>  content = models.TextField()<br>  status = models.PositiveIntegerField(choices=STATUS_CHOICES,<br>    default=DRAFT)</pre><pre>  author = models.ForeignKey(User, on_delete=models.CASCADE)<br>  categories = models.ManyToManyField(Category)<br>  <br>  date_created = models.DateTimeField(auto_now_add=True)<br>  date_updated = models.DateTimeField(auto_now=True)</pre><pre>  class Meta:<br>    ordering = [&#39;-date_created&#39;]</pre><pre>  def __str__(self):<br>    return self.title </pre><pre>  def get_absolute_url(https://medium.com/self):<br>    return reverse(&#39;cms:detail&#39;, kwargs= {<br>      &#39;slug&#39;: self.slug, &#39;pk&#39;: self.pk})</pre><p><strong>cms/admin.py</strong></p><p>Django comes with an admin app, which makes our work significantly easy. We just register our models in the admin section.</p><pre>...<br>from cms.models import Category, Post </pre><pre>class CategoryAdmin(admin.ModelAdmin):<br>  list_display = [&#39;title&#39;, &#39;slug&#39;]<br>  prepopulated_fields = {&#39;slug&#39;: [&#39;title&#39;]}</pre><pre>class PostAdmin(admin.ModelAdmin):<br>  list_display = [&#39;title&#39;, &#39;author&#39;, &#39;date_created&#39;]<br>  prepopulated_fields = {&#39;slug&#39;: [&#39;title&#39;]}</pre><pre>admin.site.register(Category, CategoryAdmin)<br>admin.site.register(Post, PostAdmin)</pre><p>To test if all these works, we make migrations with the commands</p><pre>python manage.py makemigrations</pre><p>If everything goes well, you should see something similar to this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*Z0hIbqPWNy5DPE3OxClXlQ.png" /><figcaption>caption showing makemigrations</figcaption></figure><p>Now we need to do migrations and create a super user, with commands</p><pre>python manage.py migrate<br>python manage.py createsuperuser<br></pre><p>The <em>createsuperuser</em> command prompts for username, email and password.</p><p>Start the server and go to <strong><em>/admin/</em></strong> path. Upon successful login, you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*D0Gy-Y1S4hBG0yjllUNvdw.png" /><figcaption>current admin screenshot</figcaption></figure><p>Go ahead and enter a sample post, you will notice the <em>slug</em> gets its value from the title.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*6JG2Wuktj44mcWFG_WRFRw.png" /><figcaption>snapshot, showing post entry</figcaption></figure><p>Go ahead and save it.</p><p>Next we want to show all published posts on our home page with link to each post clicked. Go back to the <em>Linear Search</em> post and change its <em>status</em> from <em>Draft</em> to <em>Published</em>.</p><p><strong>cms/views.py</strong></p><pre>from django.shortcuts import render, get_object_or_404</pre><pre>from cms.models import Post, Category</pre><pre>def home_view(request):<br>  return render(request, &#39;cms/home.html&#39;,<br>    {&#39;posts&#39;: Post.objects.filter(status=Post.PUBLISHED)})</pre><pre>def detail_view(request, slug, pk):<br>  return render(request, &#39;cms/detail.html&#39;,<br>    {&#39;post&#39;: get_object_or_404(Post, slug=slug, pk=pk)})</pre><pre>def category_post_view(request, slug):<br>  category = get_object_or_404(Category, slug=slug)<br>  return render(request, &#39;cms/category_post.html&#39;,<br>    {&#39;posts&#39;: Post.objects.filter(status=Post.PUBLISHED,<br>                                  categories=category),<br>     &#39;category&#39;: category})</pre><p><strong>cms/urls.py</strong></p><p>Modify urls.py to</p><pre>from django.urls import path</pre><pre>from cms.views import home_view, detail_view, \<br>  category_post_view</pre><pre>app_name = &#39;cms&#39;</pre><pre>urlpatterns = [<br>  path(&#39;&#39;, home_view, name=&#39;home&#39;),<br>  path(&#39;&lt;slug:slug&gt;_&lt;int:pk&gt;/&#39;, detail_view, name=&#39;detail&#39;),<br>  path(&#39;categories/&lt;slug:slug&gt;/&#39;, category_post_view,<br>    name=&#39;category_posts&#39;),<br>]</pre><p>Create a <strong><em>detail.html</em></strong> file and <strong><em>category_post.html</em></strong> file in <strong><em>templates/cms</em></strong> folder and add the below code.</p><p><strong>templates/cms/detail.html</strong></p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% block title %}{{post.title}}{% endblock %}</pre><pre>{% block content %}</pre><pre>&lt;h2&gt;{{post.title}}&lt;/h2&gt;<br>&lt;p&gt;&lt;b&gt;categories: &lt;/b&gt;<br>  {% for c in post.categories.all %}<br>  &lt;a hef=&quot;{{c.get_absolute_url}}&quot;&gt;{{c.title}}&lt;/a&gt;,<br>  {% endfor %}<br>&lt;/p&gt;<br>&lt;p&gt;updated on: {{post.date_updated}}&lt;/p&gt;<br>&lt;p&gt;created on: {{post.date_created}}&lt;/p&gt;<br>&lt;p&gt;by {{post.author}}&lt;/p&gt;</pre><pre>{{post.content|safe}}</pre><pre>{% endblock %}</pre><p><strong>templates/cms/category_post.html</strong></p><p>Add this to the category_post file</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% block title %}{{category}}| Category{% endblock title %}</pre><pre>{% block content %}</pre><pre>&lt;h2&gt;Showing posts for category &#39;{{category}}&#39;&lt;/h2&gt;<br>&lt;hr&gt;<br>{% if posts %}<br>{% for post in posts %}</pre><pre>&lt;h2&gt;{{post.title}}&lt;/h2&gt;<br>&lt;p&gt;&lt;b&gt;updated on:&lt;/b&gt; {{post.date_updated}}&lt;/p&gt;<br>&lt;p&gt;&lt;b&gt;by&lt;/b&gt; {{post.author}}&lt;/p&gt;<br>{{post.content|striptags|truncatewords:15}}<br>&lt;a href=&quot;{{post.get_absolute_url}}&quot;&gt;Read More&lt;/a&gt;<br>&lt;hr&gt;</pre><pre>{% endfor %}<br>{% endif %}</pre><pre>{% endblock %}</pre><p><strong>templates/cms/home.html</strong></p><p>Add this below the <strong><em>&lt;h2&gt;Welcome to SimpleCMS&lt;/h2&gt;</em></strong></p><pre>&lt;hr&gt;<br>{% if posts %}<br>{% for post in posts %}<br>  &lt;h2&gt;{{post.title}}&lt;/h2&gt;<br>  &lt;p&gt;&lt;b&gt;categories:&lt;/b&gt;<br>    {% for c in post.categories.all %}<br>    &lt;a href=&quot;{{c.get_absolute_url}}&quot;&gt;{{c.title}}&lt;/a&gt;,<br>    {% endfor %}<br>  &lt;/p&gt;<br>  &lt;p&gt;by {{post.author}}&lt;/p&gt;<br>  &lt;p&gt;&lt;b&gt;updated on:&lt;/b&gt; {{post.date_updated}}&lt;/p&gt;</pre><pre>  {{post.content|striptags|truncatewords:15}}</pre><pre>  &lt;a href=&quot;{% url &#39;cms:detail&#39; post.slug post.pk %}&quot;&gt;Read More&lt;/a&gt;  <br>  &lt;hr&gt;<br>{% endfor %}<br>{% endif %}</pre><p>If we save these and run the server, we should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*eDapmmygoZZb3QkinRdXiA.png" /><figcaption>current homepage</figcaption></figure><p>On clicking Read More, You see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*j3Wketh2qu222QPgeDRxIw.png" /><figcaption>snapshot showing post detail page</figcaption></figure><p>Wow! we have displayed our post entry. But notice that our <em>template&lt;typename T&gt;</em> didn’t render properly. Well this is because inside the <em>pre</em> tag we didn’t use <em>&amp;lt;</em> and <em>&amp;gt;</em> We can go back and correct it, but what if we need to write less than or equal, or less than in expressions. To solve these problem we use Pygments.</p><p>Install pygments with</p><pre>python -m pip install Pygments</pre><p>Create a <strong><em>templatetags</em></strong> folder inside cms app and create to files <strong><em>__init__.py</em></strong> and <strong><em>code_tags.py </em></strong>and<strong><em> cms_tags.py</em></strong></p><p><strong>cms/templatetags/code_tags.py</strong></p><p>The <strong><em>do_code</em></strong> tag a also a slight modification of the one gotten <a href="https://djangosnippets.org/snippets/1213/">here</a>. It enables us to perform formatting and highlighting using pygments.</p><pre>from django import template</pre><pre>from pygments import highlight<br>from pygments.lexers import <strong>*</strong><br>from pygments.formatters import HtmlFormatter</pre><pre>register = template.Library()</pre><pre>@register.tag(name<strong>=</strong>&#39;code&#39;)<br>def do_code(parser,token):<br>  code <strong>=</strong> token<strong>.</strong>split_contents()[<strong>-</strong>1]<br>  nodelist <strong>=</strong> parser<strong>.</strong>parse((&#39;endcode&#39;,))<br>  parser<strong>.</strong>delete_first_token()<br>  return CodeNode(code,nodelist)<br>    <br>class CodeNode(template<strong>.</strong>Node):<br>  def __init__(self,lang,code):<br>    self<strong>.</strong>lang <strong>=</strong> lang<br>    self<strong>.</strong>nodelist <strong>=</strong> code<br>        <br>  def render(self,context):<br>    try:        <br>      language <strong>=</strong> template<strong>.</strong>Variable(self<strong>.</strong>lang)<strong>.</strong>resolve(context)<br>    except:<br>      language <strong>=</strong> self<strong>.</strong>lang<br>    code <strong>=</strong> self<strong>.</strong>nodelist<strong>.</strong>render(context)<br>    try:<br>      lexer <strong>=</strong> get_lexer_by_name(language)<br>    except:<br>      try:<br>        lexer <strong>=</strong> guess_lexer(code)<br>      except:<br>        lexer <strong>=</strong> PythonLexer()<br>    return highlight(code,lexer,HtmlFormatter(linenos<strong>=</strong>&#39;table&#39;))</pre><p><strong>cms/templatetags/cms_tags.py</strong></p><p>The<strong><em> render_as_template</em></strong> tag, a slight modification of the one gotten <a href="https://djangosnippets.org/snippets/1373/">here</a>. This allows us to use templatetags in database fields. Thus we can load tags and use them when entering data.</p><pre>from django import template</pre><pre>register = template.Library()</pre><pre>@register.tag(name=&#39;render_as_template&#39;)<br>def render_as_template(parser, token):<br>  tokens <strong>=</strong> token<strong>.</strong>split_contents()<br>  if len(tokens) !<strong>=</strong>2:<br>    raise template.TemplateSyntaxError(&quot;expects 1 argument&quot;)    <br>  return RenderAsTemplateNode(tokens[1])</pre><pre>class RenderAsTemplateNode(template<strong>.</strong>Node):<br>  def __init__(self, item):<br>    self.item <strong>=</strong> item<br><br>  def render(self, context):<br>    try:<br>      item <strong>=</strong> template.Variable(self<strong>.</strong>item)<strong>.</strong>resolve(context)<br>      return template.Template(item).render(context)<br>    except template<strong>.</strong>VariableDoesNotExist:<br>      return &#39;&#39;</pre><p>templates/cms/detail.html</p><p>Modify detail.html to</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% load cms_tags %}</pre><pre>{% block title %}{{post.title}}{% endblock %}</pre><pre>{% block content %}</pre><pre>&lt;h2&gt;{{post.title}}&lt;/h2&gt;<br>&lt;p&gt;&lt;b&gt;categories:&lt;/b&gt;<br>  {% for c in post.categories.all %}<br>  {{c.title}},<br>  {% endfor %}<br>&lt;/p&gt;<br>&lt;p&gt;&lt;b&gt;updated on:&lt;/b&gt; {{post.date_updated}}&lt;/p&gt;<br>&lt;p&gt;&lt;b&gt;created on:&lt;/b&gt; {{post.date_created}}&lt;/p&gt;<br>&lt;p&gt;by {{post.author}}&lt;/p&gt;</pre><pre>{% render_as_template post.content %}</pre><pre>{% endblock %}</pre><p>Also remove the <em>pre</em> tag from our <em>data field </em><strong><em>content</em></strong> entry and instead load code_tags with <strong><em>{% load code_tags %}</em></strong>. Also, wrap our code round <strong><em>{% code ‘python’ %} {% endcode %}</em></strong></p><p>After we run the server, you notice that our code has line numbers, you can check the html source to see that syntax highlighting was done. You should see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*4UEHFpkQpeoawpmr3b8qTA.png" /></figure><p>Up to this point we have handled almost everything in our checklist apart from integrating the disqus comment system.</p><p>Move to part 3</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9916e593ba71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/a-first-project-a-simple-cms-part-2-9916e593ba71">A First Project — A Simple CMS : Part 2</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First project — A Simple CMS]]></title>
            <link>https://medium.com/django-framework-real-world-projects/first-project-a-simple-cms-78e53f7bebff?source=rss----86ab17bb8091---4</link>
            <guid isPermaLink="false">https://medium.com/p/78e53f7bebff</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chukwunonso Nwafor]]></dc:creator>
            <pubDate>Sat, 30 Nov 2019 07:59:01 GMT</pubDate>
            <atom:updated>2020-03-20T02:16:55.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>First project — A Simple CMS</h3><p><strong>updated</strong> for python <strong>3.8.0</strong> and django <strong>2.2.7</strong></p><p>“The web framework for perfectionists with deadlines”. Yeah right. Wrote my first program with ease but have spent months now combing its documentation and hacking open source projects I come across (and can handle alone within a reasonable time-frame). I still feel like a beginner. DJANGO……. DAMN YOU.</p><p>Why did I even bring this on myself: well for starters — <a href="http://algorithmcity.com/">Algorithmcity</a>. Yep, its still down, want to put it up again (Apologies to its readers). What I had before… well doesn’t fully represent what I have in mind. I was hacking a lot of things in php on wordpress framework. Decided to rebuild with django (good news), now I spend more time working with django than implementing my beloved algorithms.</p><p>GOODNEWS… I have placed a rule, AFTER my first 20 django projects posts (mainly cms), I will put up <a href="http://algorithmcity.com/">Algorithmcity</a> with the knowledge I have acquired however imperfect it is. Who knows, after all these, I might be worthy of the title python developer.</p><h4><strong>Meet Django</strong></h4><p>A python web framework that supports rapid web development. It follows the MTV(Model-Template-View) pattern.</p><p><strong>First things first:</strong></p><p>Create a project directory, create a virtual environment in it, activate it and install django, create the django project in it.</p><p>I assume you have <em>python 3.</em><strong><em>xx</em></strong> installed. Check <a href="https://www.python.org/downloads/">python download</a></p><p>Am running this on window, some commands would be different on Mac and Linux. For example, creating and changing directories, activating venv. Do a little googling.</p><p>I am also using the <a href="https://code.visualstudio.com/download">Visual Studio Code</a> editor.</p><pre><strong>md</strong> simplecms &amp;&amp; <strong>cd</strong> simplecms<br>python -m venv env &amp;&amp; env\Scripts\activate<br>python -m pip install Django==2.2.7<br>django-admin startproject simplecms .</pre><p><strong>simplecms/urls.py</strong></p><p>Import <em>HttpResponse</em> from <em>django.http</em> and add a view to the root path that returns helloworld.</p><pre>...<br>from django.http import HttpResponse</pre><pre>urlpatterns = [<br>  ...<br>  path(&#39;&#39;, lambda request: HttpResponse(&#39;Helloworld&#39;)),<br>]</pre><p>Run the server using:</p><pre>python manage.py runserver</pre><p>You should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*ZM8FR9nmoxk4P9AVNFM1cA.png" /><figcaption>helloworld snapshot</figcaption></figure><p>We can render a template by editing <strong><em>simplecms/urls.py </em></strong>and substituting <strong><em>from django.http import HttpResponse</em></strong> with <strong><em>from django.shortcuts import render</em></strong></p><pre>...<br>from django.shortcuts import render</pre><pre>urlpatterns = [<br>  ...<br>  path(&#39;&#39;, lambda request: render(request, &#39;home.html&#39;)),<br>]</pre><p>or by using <em>TemplateView</em></p><pre>...<br>from django.views.generic import TemplateView</pre><pre>urlpatterns = [<br>  ...<br>  path(&#39;&#39;, TemplateView.as_view(template_name=&#39;home.html&#39;)),<br>]</pre><p>For the template create a <strong><em>templates</em></strong> directory in your root directory and the file <strong><em>home.html</em></strong> to have</p><p><strong>templates/home.html</strong></p><p>Here you enter</p><pre>&lt;h2&gt;Helloworld&lt;/h2&gt;</pre><p>Oh, lest I forget add <strong><em>os.path.join(BASE_DIR, ‘templates’)</em></strong> to <strong><em>DIRS</em></strong> in <strong><em>TEMPLATES</em></strong> located in the <strong><em>simplecms/settings.py</em></strong> file.</p><p>You should now see a <strong><em>h2</em></strong> formatted <em>Helloworld</em></p><h4>A little Explanation</h4><p>When we use our web browsers, we perform a request (get, post, head etc) and a server that hosts whatever content we specify at the entered URL returns a response.</p><p>Well that is just what we did above.</p><ul><li><em>path(‘ ‘,</em> <em>lambda request: HttpResponse(‘Helloworld’))</em> simply says, if we are given that path, return a <em>Helloworld</em> response</li><li><em>path(‘ ‘, lambda request: render(request, ‘home.html’))</em> simple says, if we are given that path, render the template <em>home.html</em> and return it as response.</li></ul><h4>The SimpleCMS Project</h4><p>Now we focus on our first project.</p><p><strong>Project Checklist</strong></p><ul><li>Content posts with 1 or more categories, date created and updated, the user that posted it.</li><li>URLS showing all posts, a detailed post, posts of a particular category,</li><li>Templatetags that does code highlighting using Pygments</li><li>Comment system using disqus</li></ul><p>More on to <a href="https://medium.com/django-framework-real-world-projects/a-first-project-a-simple-cms-part-2-9916e593ba71">part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e53f7bebff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-framework-real-world-projects/first-project-a-simple-cms-78e53f7bebff">First project — A Simple CMS</a> was originally published in <a href="https://medium.com/django-framework-real-world-projects">Django Framework — Real World Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>