<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by zonecc on Medium]]></title>
        <description><![CDATA[Stories by zonecc on Medium]]></description>
        <link>https://medium.com/@bkevery?source=rss-c830c6a053f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PlXmUgMI2sOLOb2u7KnjcQ.jpeg</url>
            <title>Stories by zonecc on Medium</title>
            <link>https://medium.com/@bkevery?source=rss-c830c6a053f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:18:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bkevery/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Connect to Postgres using psycopg2 and make it happen the Andela way (part 2)]]></title>
            <link>https://medium.com/@bkevery/connect-to-postgres-using-psycopg2-and-make-it-happen-the-andela-way-part-2-aeeb356de8c5?source=rss-c830c6a053f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeeb356de8c5</guid>
            <category><![CDATA[psycopg2]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[zonecc]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 22:26:06 GMT</pubDate>
            <atom:updated>2019-02-18T22:26:06.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*xxMTz5qD6eCka4yL5P27qQ.png" /><figcaption>write tests</figcaption></figure><p>As I said, am totally lazy so I kinda like hacks and workarounds. I mean, making it simple. In my method of connecting to the database, I did not include a way for anyone to drop tables after writing tests for a specific view or model. My reason is this, I wanted to create only the needed users and create them only once. If I want to test a book I create the book once and use it all along. Let me write tests and add some views to elaborate further.</p><p>So we’ll start with the book adding view. Here’s what we want to be specific to this view:</p><ul><li>any user can access the book</li><li>only an admin can add a book</li></ul><p>Here are the adjustments we will be making:</p><ul><li>adding token based authentication</li><li>adding book adding and viewing views 😆(view..view)</li><li>adding tests for the views</li><li>adding some validations</li></ul><p>Well, let’s get started. I will be using pyjwt and so we’ll start by adding the login function. First things first, we’ll install pyjwt.</p><pre>$ pip3 install pyjwt<br>$ pip3 freeze &gt;&gt; requirements.txt</pre><p>Now let’s import the module and write our view. Though we have installed pyjwt, we are going to import jwt. In this login function, we are going to check if a user exists in the database. Once the user is found, we are going to get some specific details which are the user:</p><ul><li>admin status</li><li>username</li><li>id</li></ul><p>Once we collect this data, we are going to add it to our payload. The payload is the data that will be encoded in our token. When decoding the token we will get back this data. So we are going to update our user view function.</p><ul><li>Let’s add a get user method in the user module. I’ll use a static method in the get user method. Why? With a static method, I don&#39;t have to add parameters to the user class which requires some list of fields. We will query using the username.</li></ul><pre>#app/api/models/user.py<br>&quot;&quot;&quot; user models &quot;&quot;&quot;<br>import datetime<br>import psycopg2<br>from.database import DatabaseConnection as db_conn</pre><pre>TIME_NOW = datetime.datetime.utcnow()</pre><pre>class User(db_conn):<br>    &quot;&quot;&quot;docstring for User&quot;&quot;&quot;<br>    def __init__(self, user_data, isAdmin=False):<br>        self.name = user_data[0]<br>        self.uname = user_data[1]<br>        self.email = user_data[2]<br>        self.password = user_data[3]<br>        self.now = datetime.datetime.utcnow()<br>        self.isAdmin = isAdmin</pre><pre>def create_new_user(self):<br>        &quot;&quot;&quot; creates/adds a new user to the users table&quot;&quot;&quot;<br>        query = &quot;&quot;&quot; INSERT INTO users(name, username,<br>                email, password, registerdate, isAdmin)<br>                VALUES( &#39;{}&#39;, &#39;{}&#39;,&#39;{}&#39;,&#39;{}&#39;, &#39;{}&#39;, &#39;{}&#39;)    <br>        &quot;&quot;&quot;.format(self.name, self.uname, self.email,<br>                self.password, self.now, self.isAdmin)     <br>        self.save_incoming_data_or_updates(query)</pre><pre>@staticmethod<br>def get_user_data(username):<br>     &quot;&quot;&quot; Get single user data using username &quot;&quot;&quot;<br>     query = &quot;&quot;&quot; <br>           SELECT * FROM users WHERE username = {}<br>             &quot;&quot;&quot;.format(username)<br>     user_info = db_conn.fetch_single_data_row(db_conn, query)<br>     &quot;&quot;&quot; the db_conn in the fetch method serves as self in a ststicmethod &quot;&quot;&quot;<br>     return user_info</pre><ul><li>we can now add the user login view</li></ul><pre>&quot;&quot;&quot;contains all endpoints for user functions such as signup and login &quot;&quot;&quot;</pre><pre>import os<br>import datetime<br>import jwt<br>from flask import Blueprint, request, jsonify<br>from ..models.user import User</pre><pre>user_blue = Blueprint(&quot;ap1v2&quot;, __name__)<br>KEY = os.getenv(&quot;SECRET&quot;)</pre><pre>@user_blue.route(&quot;/signup&quot;, methods=[&quot;POST&quot;])<br>def user_signup():<br>    &quot;&quot;&quot;endpoint for user to create account &quot;&quot;&quot;<br>    try:<br>        user_data = request.get_json()<br>        name = user_data[&quot;name&quot;]<br>        username = user_data[&quot;username&quot;]<br>        email = user_data[&quot;email&quot;]<br>        password = user_data[&quot;password&quot;]<br>    except Exception:<br>        return jsonify({<br>            &quot;error&quot; : &quot;invalid user data input&quot;,<br>            &quot;message&quot; : &quot;missing either name, username, email or password&quot;,<br>           &quot;status&quot; : 400<br>            }), 400</pre><pre>    new_user = User([name,username,email,password])<br>    new_user.create_new_user()<br>    return jsonify({<br>        &quot;status&quot;: 201, &quot;message&quot;: &quot;user created successfully&quot;}), 201</pre><pre>@user_blue.route(&quot;/login&quot;, methods=[&quot;POST&quot;])<br>def user_login():<br>    try:<br>        login_data = request.get_json()<br>        print(login_data)<br>        username = login_data[&quot;username&quot;]<br>        password = login_data[&quot;password&quot;]<br>    except Exception as error:<br>        return jsonify({<br>            &quot;status&quot;: 400,<br>            &quot;error&quot;: &quot;missing username and password fields&quot;,<br>            &quot;message&quot;: &quot;username and password fields are required&quot;<br>           }), 400</pre><pre>    user_exists = User.get_user_data(username)<br>    if not user_exists:<br>       return jsonify({<br>          &quot;status&quot;: 401,<br>          &quot;error&quot;: &quot;user not found&quot;,<br>          &quot;message&quot;: &quot;user with username does not exist&quot;<br>        }), 401<br>    #else the user was found<br>    if password != user_exists[4]:<br>        return jsonify({<br>            &quot;status&quot;: 401,<br>            &quot;error&quot;: &quot;invalid password&quot;,<br>            &quot;message&quot;: &quot;the password you entered is icorrect&quot;<br>          }), 401</pre><pre>    user_id = user_exists[0]<br>    user_admin_status = user_exists[-1]<br>    exp = datetime.datetime.utcnow()+datetime.timedelta(minutes=60)<br>    #exp time when token expires I like 1hour<br>    token = jwt.encode({<br>       &quot;username&quot;: username,<br>       &quot;id&quot;: user_id,<br>       &quot;admin&quot;: user_admin_status,<br>      &#39;exp&#39;: exp}, KEY, algorithm=&#39;HS256&#39;)<br>    <br>    return jsonify({<br>        &quot;status&quot;: 200,<br>        &quot;token&quot;: token.decode(&quot;utf-8&quot;, KEY),<br>        &quot;message&quot;: &quot;Logged in successfully&quot;<br>       })</pre><p># with that our user is validated and will log in if credentials are found and match ones in the DB. I created a user codezonecc in my database and I will test if he logs in successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeOTpnInASL1ibLKR8nOyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StUXVZyUelRIh_o7Zfhhlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YL1yXK0P-N1SjAFZESonIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2iN4uQV0zZO4zIx_paCpw.png" /></figure><p>On the successful login, invalid username, no data and with an incorrect password.</p><p>Let’s now add the token decorator. This may pretty much look like yours if you already have one. Just keeping it simple so that we all get what’s going on.<br>We’ll create a base_validations.py in the utils folder.</p><pre>#app/api/utils/base_validations.py<br>import os<br>from functools import wraps<br>import jwt<br>from flask import jsonify, abort, make_response, request</pre><pre>KEY = os.getenv(&quot;SECRET&quot;)</pre><pre>def token_required(f):<br>    @wraps(f)<br>    def decorated(*args, **kwargs):<br>        token = None<br>        if &quot;x-access-token&quot; in request.headers:<br>            token = request.headers[&#39;x-access-token&#39;]<br>        else:<br>           abort(make_response(jsonify({<br>              &quot;status&quot;: 401,<br>              &quot;error&quot;: &quot;Token is missing&quot;}), 401))<br>       try:<br>           data = jwt.decode(token, KEY, algorithms=&quot;HS256&quot;)<br>           current_user = [data[&quot;id&quot;], data[&quot;username&quot;], data[&quot;admin&quot;]]<br>       except (jwt.InvalidTokenError, jwt.ExpiredSignatureError, TypeError):<br>           return jsonify({&quot;error&quot;: &quot;Token is invalid or expired&quot;,<br>                 &quot;status&quot;: 401}), 401<br>       return f(current_user, *args, **kwargs)<br>    return decorated</pre><p>Remember we encoded username, id, and admin_status. So now upon decoding, we get back the data in this format:</p><ul><li>user_id = current_user[0]</li><li>username = current_user[1]</li><li>admin_status = current_user[2]</li></ul><p>Now, let&#39;s add a book:<br>Remember “ only admins can add books”. In the views folder, I’ll add a book_views.py. Before this, we need to create a books model to insert and get the data. Let’s also create a book.py in the models&#39; folder.</p><p>Our books lets say will contain:</p><ul><li>a book title</li><li>an author</li><li>some description</li><li>create date</li><li>created by (admin id who adds the book)</li></ul><pre>#app/api/models/book.py<br>&quot;&quot;&quot; book models &quot;&quot;&quot;</pre><pre>import datetime<br>import psycopg2<br>from.database import DatabaseConnection as db_conn</pre><pre>TIME_NOW = datetime.datetime.utcnow()</pre><pre>class Book(db_conn):<br>    def __init__(self, book_data):<br>        self.title = book_data[0]<br>        self.author = book_data[1]<br>        self.description = book_data[2]<br>        self.creator = book_data[3]<br>        self.create_at = datetime.datetime.utcnow()</pre><pre>    def add_a_book_to_store(self):<br>        query = &quot;&quot;&quot;<br>           INSERT INTO books(userid, title, description, Author, <br>               postedon)VALUES(&#39;{}&#39;, &#39;{}&#39;, &#39;{}&#39;, &#39;{}&#39;, &#39;{}&#39;)<br>            &quot;&quot;&quot;.format(self.creator, self.title, self.description, <br>                self.author, self.create_at)</pre><pre>        self.save_incoming_data_or_updates(query)</pre><p>Now we’ll add a view for posting the book.</p><pre>#app/api/views/book_views.py<br>import os<br>from flask import Blueprint, request, jsonify<br>from ..models.book import Book<br>from ..utils.base_alidations import token_required</pre><pre>v2_blue = Blueprint(&quot;apiv2&quot;, __name__)</pre><pre>@v2_blue.route(&quot;/books&quot;, methods=[&#39;POST&#39;])<br>@token_required<br>def post_a_book(current_user):<br>    user_id = current_user[0]<br>    admin_status = current_user[2]<br>    if not admin_status:<br>        &quot;&quot;&quot; Check if admin status is false means user is not admin<br>        &quot;&quot;&quot;<br>        return jsonify({<br>            &quot;status&quot;:403,<br>            &quot;error&quot;: &quot;unauthorized user&quot;,<br>            &quot;message&quot;: &quot;only admins can add books&quot;<br>          }), 403<br>    try:<br>       book_data = request.get_json()<br>       book_title = book_data[&quot;title&quot;]<br>       book_author = book_data[&quot;author&quot;]<br>       book_description = book_data[&quot;description&quot;]<br>    except Exception:<br>       return jsonify({<br>          &quot;status&quot;: 400,<br>          &quot;error&quot;: &quot;some required fields are missing&quot;,<br>          &quot;message&quot;: &quot;missing either title, author or description&quot;<br>         }), 400</pre><pre>    new_book_data = [book_title, book_author, book_description, <br>             user_id]<br>    new_book = Book(new_book_data)<br>    new_book.add_a_book_to_store()<br>    return jsonify({<br>        &quot;status&quot;: 201,<br>        &quot;data&quot;: {<br>          &quot;Book Name&quot; : book_title,<br>          &quot;Book Author&quot;: book_author,<br>          &quot;Book Description&quot;: book_description<br>         },<br>       &quot;message&quot;: &quot;Book added successfully&quot;<br>       }),201</pre><p>With that, let’s test on insomnia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zaohLw0N-gKGZy_aUv5Bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsHOLfQNlaZZpFwCF-xW3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUK1tL1AKve-bK9Vjmu-hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giFn1ajnZr6poMb-jdCnKA.png" /></figure><p>And from that, we see that our app is ok. Your assignment is to create the get books views and make validations. I just wanted to give you the basics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeeb356de8c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect to Postgres using psycopg2 and make it happen the Andela way]]></title>
            <link>https://medium.com/@bkevery/connect-to-postgres-using-psycopg2-and-make-it-happen-the-andela-way-ceb6b1a12b02?source=rss-c830c6a053f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceb6b1a12b02</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[psycopg2]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[zonecc]]></dc:creator>
            <pubDate>Wed, 13 Feb 2019 01:17:40 GMT</pubDate>
            <atom:updated>2019-02-13T12:41:02.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>Connect to Postgres using psycopg2 and make it happen the Andela way (part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7wuGVzqeLhHicboS5Z8qA.jpeg" /></figure><p>Psycopg2 is a python-Postgres library😍. Yeah, we can call it a p-p love story. But jokes aside, this is not the only method available to connect to Postgres database in python. You can also use an ORM (Object Relation Marker) like <em>SQLAlchemy which is really simple but maaahhn😣😣.. that’s not the </em><strong><em>Andela Way.</em></strong></p><p>So what’s the difference between an ORM and Psycopg2? This is simple, the difference is that with an ORM it’s like the queries are prewritten in methods. All you do is just call a method and there you have your result. However, with Psycopg2, you have to write your own raw SQL queries. Quite some work, right?? But am here to your rescue😁😁.. I’ll give you a simple connection method that you’ll enjoy. Don’t forget to leave a clap at the end of this read😉.</p><p>So we’ll create a simple bookstore program that we will use all through. And as always we start with the setting up the project. Am not going to do a lot of testing and Travis but in case you feel you need a write-up on testing just leave a comment and I’ll do that. The main purpose of this write is to help you be able to differentiate your development database from your test database automatically without using the flask app context and related staff. To me, app context was actual hell 😆. Took me 3 days not to solve but to get a workaround. Anyway, if your cool with it, just stick to what suits you best.</p><p>So now lets setup out file system:<br>“always remember to include __init__.py files in all your subdirectories except the main working directory”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaNfRaPVrWh1CAWhICStoQ.png" /></figure><p>That’s the basic file system, app, instance, and test folders. Am not doing a v1 or v2 since its a simple basic database application. I am using vs code, one of the best editors I’ve used so far.</p><p>In your psql console, you can create two database schemas. I’ll name my databases bookstore and testbookstore.</p><pre>$ sudo -u postgres psql postgres<br>psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1))<br>Type &quot;help&quot; for help.</pre><pre>postgres=# create database bookstore;<br>CREATE DATABASE<br>postgres=# create database testbookstore;<br>CREATE DATABASE<br>postgres=# \q</pre><pre>#now we have created our databases lets get to it</pre><p>We can now set up our .env file. But first, let’s create our virtual environment.<br>check out this link to install python3 virtualenv for creating your env <a href="https://gist.github.com/Geoyi/d9fab4f609e9f75941946be45000632b">https://gist.github.com/Geoyi/d9fab4f609e9f75941946be45000632b</a></p><pre>$ virtualenv env<br>Using base prefix &#39;/usr&#39;<br>New python executable in /var/codezonecc/book-store/env/bin/python3<br>Also creating executable in /var/codezonecc/book-store/env/bin/python<br>Installing setuptools, pip, wheel...<br>done.</pre><pre>#now lets edit our env file using nano<br>$ nano .env<br># we are adding a couple of things here</pre><pre>source env/bin/activate<br>export FLASK_APP=&quot;run.py&quot;<br>export SECRET=&quot;use_some_strong_key_not_some_random_text_like_this&quot;<br>export APP_SETTING=development<br>export App_Test=testing<br>export FLASK_ENV=development</pre><pre>export Test_Database=&quot;postgresql://postgres:postgres@localhost/testbookstore&quot;<br>export Main_Database=&quot;postgresql://postgres:postgres@localhost/bookstore&quot;</pre><p>A brief explanation of what the .env does:<br>* Starts the virtual environment<br>* Sets the basic app configuration environment to development<br>* Last two lines are called database URIs/URLs and are what we use to connect to the database with<br>** dbtype://dbusers:password@dbhost/dbname**</p><p>Now, lets set up our configurations. In the instance folder, we’ll create a file called config.py and mine will look like this:</p><pre>&quot;&quot;&quot; API config File &quot;&quot;&quot;<br>import os</pre><pre>class Config(object):<br>    &quot;&quot;&quot; Parent configuration class &quot;&quot;&quot;</pre><pre>DEBUG = False<br>    TESTING = False<br>    Database_Url = os.getenv(&quot;Main_Database&quot;)<br>    SECRET_KEY = os.getenv(&quot;SECRET&quot;)</pre><pre>class DevelopmentConfig(Config):<br>    &quot;&quot;&quot; Configuration for development environment &quot;&quot;&quot;<br>    DEBUG = True<br>    Database_Url = os.getenv(&quot;Main_Database&quot;)</pre><pre>class TestingConfig(Config):<br>    &quot;&quot;&quot; Configuratio(env) zonecc@trevor:/var/codezonecc/My Diary$n for the testing environment &quot;&quot;&quot;<br>    TESTING = True<br>    DEBUG = True<br>    Database_Url = os.getenv(&quot;Test_Database&quot;)</pre><pre>#for heroku in case I decide to host the app but that&#39;s it<br>class ProductionConfig(Config):<br>    &quot;&quot;&quot; Configuration for the production environment &quot;&quot;&quot;<br>    DEBUG = False<br>    TESTING = False<br>    Database_Url = os.getenv(&quot;DATABASE_URL&quot;)</pre><pre>app_config = {<br>    &#39;development&#39;: DevelopmentConfig,<br>    &#39;testing&#39;: TestingConfig,<br>    &#39;production&#39;: ProductionConfig<br>}</pre><p>We can now start our virtual environment:</p><pre>$ source .env</pre><pre>$ # then you should get a result like below is in my case yours may be a little diferent</pre><pre>(env) zonecc@zonecc:/var/codezonecc/book-store$</pre><p>Am an Ubuntu user and have my /var/codezonecc as my main working dir.</p><p>Ok. We’ve set all that up but don’t know what the app will do. Basically, the app admins will be able to add books to the bookstore and users will be able to access these books. I don’t think I’ll do the app fully now just to stick to demonstrating how the database works but later maybe I’ll finish it? 💭<br>So I’ll just do the post user endpoint and test it so you see the database distinction. If I get time I’ll do the whole app and make it better.</p><p>Having that in mind lets setup our database. In your models’ folder let’s create a file called database.py and another one called maindb.py (the naming is on you). This will be in charge of the connection. I’ll not do any kind of validations but if you need me to leave a comment or just hit my inbox.</p><p>We start with maindb.py where we write our initial queries like table creation and dropping.</p><p>Our users shall have: <br> * Name<br>* username<br>* email<br>* password</p><p>Our books shall have:<br>* Title<br>* Description<br>* Author<br>* Date posted<br>* Users Id</p><p>Two kinds of transactions can be associated with the books, ie. posting and getting. Posting is for admins and getting is for normal users.</p><pre>import os<br>import datetime</pre><pre>def drop_table_if_exists():<br>    &quot;&quot;&quot; Deletes all tables&quot;&quot;&quot;<br>    drop_users = &quot;&quot;&quot; DROP TABLE IF EXISTS users &quot;&quot;&quot;<br>    drop_books = &quot;&quot;&quot; DROP TABLE IF EXISTS meetups &quot;&quot;&quot;<br>    return [drop_books, drop_users]</pre><pre>def set_up_tables():<br>    create_users_table = &quot;&quot;&quot;<br>         CREATE TABLE IF NOT EXISTS users (<br>         id serial PRIMARY KEY,<br>         name VARCHAR(30) NOT NULL,<br>         username VARCHAR(40) NOT NULL UNIQUE,<br>         email VARCHAR(60) NOT NULL UNIQUE,<br>         password VARCHAR(200) NOT NULL,<br>         registerdate TIMESTAMP,<br>         isAdmin BOOLEAN DEFAULT False);&quot;&quot;&quot;</pre><pre>    create_books_table = &quot;&quot;&quot;<br>        CREATE TABLE IF NOT EXISTS books (<br>        id serial PRIMARY KEY,<br>        userid INTEGER NOT NULL,<br>        title VARCHAR(100) NOT NULL,<br>        description VARCHAR NOT NULL,<br>        Author VARCHAR(200) NOT NULL,<br>        postedon TIMESTAMP);&quot;&quot;&quot;</pre><pre>    return [create_books_table, create_users_table]<br></pre><pre>def create_admin(connect):<br>    query = &quot;&quot;&quot;<br>        INSERT INTO users(name, username, email, password,<br>        registerdate, isAdmin)<br>        VALUES(&#39;adminUser&#39;, &#39;admin&#39;, &#39;admin@admin.dns&#39;, &#39;$$PAss12&#39;,<br>        &#39;{}&#39;,&#39;True&#39;)&quot;&quot;&quot;.format(datetime.datetime.utcnow())</pre><pre>    # prevents trying duplicating admin if already exists<br>    get_admin = &quot;&quot;&quot;SELECT * from users WHERE username = &#39;admin&#39;&quot;&quot;&quot;<br>    cur = connect.cursor()<br>    get_admin = cur.execute(get_admin)<br>    get_admin = cur.fetchone()<br>    if get_admin:<br>        pass<br>    else:<br>        cur.execute(query)<br>        connect.commit()</pre><p>As you can see above are queries to create tables and an admin on app start. They are only created if they don’t exist.<br>Now let’s create the database.py file.</p><pre>&quot;&quot;&quot;&quot; Main connection to the postgres database &quot;&quot;&quot;<br>import psycopg2<br>from maindb import set_up_tables, drop_table_if_exists, create_admin</pre><pre>class DatabaseConnection:<br> &quot;&quot;&quot; Handles the main connection to the database of the app <br>       setting &quot;&quot;&quot;</pre><pre> def __init__(self, db_url):<br>   &quot;&quot;&quot; initialize the class instance to take a database url as a <br>         parameter&quot;&quot;&quot;</pre><pre>   try:<br>        # Am really lazy even at typing<br>        # I use global conn and cur to prevent doing  <br>        # self.conn/sel.cur</pre><pre>        global conn, cur</pre><pre>        # actualconnection<br>        conn = psycopg2.connect(db_url)<br>        cur = conn.cursor()<br>    except Exception as error:<br>        print(error)</pre><pre>  def create_tables_and_admin(self):<br>    &quot;&quot;&quot; creates all tables &quot;&quot;&quot;<br>    all_tables_to_create = set_up_tables()<br>    for query in all_tables_to_create:<br>    cur.execute(query)<br>    conn.commit()<br>    create_admin(conn)</pre><pre>  def drop_all_tables(self):<br>    &quot;&quot;&quot; Deletes all tables in the app &quot;&quot;&quot;<br>    tables_to_drop = drop_table_if_exists()<br>    for query in tables_to_drop:<br>    cur.execute(query)<br>    conn.commit</pre><pre>  def fetch_single_data_row(self, query):<br>    &quot;&quot;&quot; retreives a single row of data from a table &quot;&quot;&quot;<br>    cur.execute(query)<br>    fetchedRow = cur.fetchone()<br>    return fetchedRow</pre><pre>  def save_incoming_data_or_updates(self, query):<br>    &quot;&quot;&quot; saves data passed as a query to the stated table &quot;&quot;&quot;<br>    cur.execute(query)<br>    conn.commit()</pre><pre>  def fetch_all_tables_rows(self, query):<br>    &quot;&quot;&quot; fetches all rows of data store &quot;&quot;&quot;<br>    cur.execute(query)<br>    all_data_rows = cur.fetchall()<br>    return all_data_rows</pre><p>From the above file. We have taken care of querying and creation of tables at app start. I’ll show you how in a few.<br>So now let’s use blueprints and populate some files in our app.<br>Before that, I think I missed something. We have to install some libraries and modules that we are going to use.</p><pre>$ pip3 install flask<br>$ pip3 install pyjwt <br>$ pip3 install pytest<br>$ pip3 install psycopg2 &amp;&amp; pip3 insatall psycopg2-binary</pre><pre>$ # now lets add a requirements.txt file<br>$ pip3 freeze &gt; requirements.txt</pre><p>Let’s create a user_views.py file in the views folder and for now it will look like:</p><pre>&quot;&quot;&quot;contains all endpoints for user functions&quot;&quot;&quot;<br>import os<br>import datetime<br>import jwt<br>from flask import Blueprint, request, jsonify, abort, make_response<br>v2_blue = Blueprint(&quot;ap1v2&quot;, __name__)<br>KEY = os.getenv(&quot;SECRET&quot;)</pre><p>We just want to register this blueprint. Now, let’s do this in the app/__init__.py file</p><pre>import os<br>import psycopg2<br>from flask import Flask, Blueprint, jsonify<br>from instance.config import app_config<br>from app.api.views.user_views import user_blue<br>from app.api.models.database import DatabaseConnection</pre><pre>def create_app(name_conf):<br>    # We will be using the config variable to determine the database<br>    app = Flask(__name__, instance_relative_config=True)<br>    app.config.from_object(app_config[name_conf])<br>    app.config.from_pyfile(&#39;config.py&#39;)<br>    db_url = app_config[name_conf].Database_Url</pre><pre>    print(&quot;\n\n\n&quot;, db_url, &quot;\n\n\n&quot;)<br>    <br>    DatabaseConnection(db_url)<br>    if name_conf == &quot;testing&quot;:<br>        DatabaseConnection.drop_all_tables(DatabaseConnection)<br>    DatabaseConnection.create_tables_and_admin(DatabaseConnection)<br>    app.register_blueprint(user_blue, url_prefix=&quot;/api/v2/auth&quot;)<br>    return app</pre><p>I guess I’ve already attained my intended goal of this tutorial but let me just do some little more demonstration for you. The print statement will indicate which database is being used in the given working environment.</p><p>So now let&#39;s create a test that passes to see if our test database actually creates the tables. It is as simple as:</p><pre>&quot;&quot;&quot;The user endpoints tests&quot;&quot;&quot;<br>import os<br>import unittest<br>import json<br>import psycopg2<br>from instance.config import app_config<br>from app import create_app<br>secret = os.getenv(&quot;SECRET&quot;)</pre><pre>class BaseTest(unittest.TestCase):</pre><pre>&quot;&quot;&quot; The base class for seeting user tests and tearing down &quot;&quot;&quot;</pre><pre>  def setUp(self):<br>    &quot;&quot;&quot; set the variables before each test &quot;&quot;&quot; <br>    self.app = create_app(&quot;testing&quot;)<br>    self.client = self.app.test_client()</pre><pre>    self.success_signup = {<br>        &quot;name&quot;: &quot;codezonecc&quot;,<br>        &quot;username&quot;: &quot;zonecc&quot;,<br>        &quot;email&quot;: &quot;code@zonecc.cz&quot;,<br>        &quot;phone&quot;: &quot;+09778789847&quot;,<br>        &quot;password&quot;: &quot;$$22BBkk&quot;<br>        }<br>   def tearDown(self):<br>        pass</pre><pre>class UserSignUp(BaseTest):<br>    &quot;&quot;&quot; Test signup success &quot;&quot;&quot;<br>    def test_successful_signup(self):<br>       pass</pre><p>With that, we can run the test using pytest.</p><pre>$ pytest || python3 -m pytest</pre><p>Let&#39;s check if our test database has tables in it, its the reason am not dropping mine but you’ll want to drop them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wczq2d2G-UyOHhvSfdcVGQ.png" /><figcaption>As you can see I’ve only tested and only the test database has tables.</figcaption></figure><p>Let me run the endpoint on postman and see what happens next. But first, we need to populate our run.py file. This will be the run.py:</p><pre>import os<br>from app import create_app</pre><pre>app = create_app(os.getenv(&quot;APP_SETTING&quot;))</pre><pre>if __name__ == &#39;__main__&#39;:<br>  app.run()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbQFkosxkwbA8xiUdcvoxQ.png" /><figcaption>After the flask run now it prints the bookstore URL and not test bookstore one.</figcaption></figure><p>Now let&#39;s check to see if the tables have been created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UQpsycwACzzqgIelOCQHg.png" /><figcaption>All the tables are now available.</figcaption></figure><p>So we had the file system set and everything running. The database connection was fine for both testing and development so now let’s just query the user signup.</p><p>In the models&#39; folder, we will create a file called user.py where we will query the signup. It will look like this:</p><pre>&quot;&quot;&quot; user models &quot;&quot;&quot;<br>import datetime<br>import psycopg2<br>from.database import DatabaseConnection as db_conn</pre><pre>TIME_NOW = datetime.datetime.utcnow()</pre><pre>class User(db_conn):<br>    &quot;&quot;&quot;docstring for User&quot;&quot;&quot;<br>    def __init__(self, user_data, isAdmin=False):<br>        self.name = user_data[0]<br>        self.uname = user_data[1]<br>        self.email = user_data[2]<br>        self.password = user_data[3]<br>        self.now = datetime.datetime.utcnow()<br>        self.isAdmin = isAdmin</pre><pre>    def create_new_user(self):<br>        &quot;&quot;&quot; creates/adds a new user to the users table&quot;&quot;&quot;<br>        query = &quot;&quot;&quot; INSERT INTO users(name, username,<br>                email, password, registerdate, isAdmin)<br>                VALUES( &#39;{}&#39;, &#39;{}&#39;,&#39;{}&#39;,&#39;{}&#39;, &#39;{}&#39;, &#39;{}&#39;)    <br>        &quot;&quot;&quot;.format(self.name, self.uname, self.email,<br>                self.password, self.now, self.isAdmin)     <br>        self.save_incoming_data_or_updates(query)</pre><p>In brief, am inheriting the methods I created for querying from database.py. As you noted when the app starts, the database connection class is also started meaning conn and cursor are turned on active. So when I inherit these methods, they have both conn and cursor and all I do is pass in the query then it is executed.</p><p>Now back to our user_views.py</p><pre>&quot;&quot;&quot;contains all endpoints for user endpoints &quot;&quot;&quot;<br>import os<br>import datetime<br>import jwt<br>from flask import Blueprint, request, jsonify, abort, make_response<br>from ..models.user import User</pre><pre>user_blue = Blueprint(&quot;ap1v2&quot;, __name__)<br>KEY = os.getenv(&quot;SECRET&quot;)</pre><pre>@user_blue.route(&quot;/signup&quot;, methods=[&quot;POST&quot;])<br>def user_signup():<br>    &quot;&quot;&quot;endpoint for user to create account &quot;&quot;&quot;<br>    try:<br>        user_data = request.get_json()<br>        name = user_data[&quot;name&quot;]<br>        username = user_data[&quot;username&quot;]<br>        email = user_data[&quot;email&quot;]<br>        password = user_data[&quot;password&quot;]<br>    except Exception:<br>        return jsonify({<br>           &quot;error&quot; : &quot;invalid user data input&quot;,<br>           &quot;message&quot; : &quot;missing either name, username, email or<br>                password&quot;,<br>           &quot;status&quot; : 400<br>         }), 400<br>    <br>    new_user = User([name,username,email,password])     <br>    new_user.create_new_user()<br>    return jsonify({<br>         &quot;status&quot;: 201, <br>         &quot;message&quot;: &quot;user created successfully&quot;<br>       }), 201</pre><p>After testing on insomnia, I rarely use postman, my user will be created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzVV2jtS0ZYWk585RgtBbg.png" /><figcaption>User created successfully.</figcaption></figure><p>I’ll create a couple more users and use pgadmin to display the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcGnKe6tWOWCwZlMIit7vw.png" /></figure><p>The same procedure applies for all other queries.</p><p>Thanks for reading through. Hope you got helped. Please leave as many claps as you can 😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceb6b1a12b02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>