fabiochiu/medium-articles huggingface dataset:
Quick and Easy API with Python’s Flask
By: Thiago Carvalho
Tags: Programming, Json, API, Pyhton, Flask

Flask

Flask is a Python web framework with lots of capabilities. We’ll only explore a few of those in this article—only the most essential to get us quickly hosting our JSON.

This should only take 10 minutes and less than 15 lines of code. So, without further ado, let’s install the libraries we’ll need.

pip install flask

pip install flask_restful

pip install pandas

Flask_restful will make our lives even with ready to go methods for building restful APIs, and Pandas will be mostly used for testing and reading the JSON files.

We’ll also make use of requests and json but those should come by default with Python.

Now we need a JSON file to use in this example. I’ll use https://calendarific.com/ to get the holidays for Canada in 2020. I’ll save that data and serve it in our Flask API.

Requests and JSON

If you want to use Calendarific, you’ll need to register and replace where it says ‘YOUR_KEY’ with the key they assigned you. You’re welcome to try the next steps with other APIs; there’s this great list of public APIs at GitHub you could try, or skip this part and go directly to the Flask API.

import requests

import json response = requests.get("https://calendarific.com/api/v2/holidays?&api_key=YOUR_KEY&country=CA&year=2020") with open('myfile.json', 'w') as json_file:

json.dump(response.json(), json_file)

Nice! That should get you a JSON file in your working directory.

Now let’s try to open and see what’s in this file with Pandas. Note the structure of Calendarific response:

Meta → Code

Response → Holidays →Name, Description, Country, Date…

I don’t want the full JSON; I want the Holidays part of it. So, I’ll select [‘response’][‘holidays’] .

response = requests.get("https://calendarific.com/api/v2/holidays?&api_key=YOUR_KEY&country=CA&year=2020") with open('myfile.json', 'w') as json_file:

json.dump(response.json()['response']['holidays'], json_file)

Pandas can help us check the JSON file in a friendlier format.

# pip install pandas import pandas as pd

df = pd.read_json('myfile.json')

print(df)

That’s it; we have our JSON file in our working directory. Now we can build our API to serve it!
AWS Multi-Tier Architecture
By: C R Nitheshwar
Tags: Bennett University, Capstone Project, AWS, Flask, Cloud

Our Experience

At first, it was totally chaotic, since it was the first time for either of us to configure multiple AWS services together but thankfully with the help of our mentor we were able to progress and work on it.

Figure 4: Customer Churn Model

Our project is more focused on the architecture to provide better security and high availability for the website. Our main backend part was a Machine learning model which predicts the churn of customers. We first preprocessed the data by cleaning the data and checked any duplicate or null values are present or not then visualized the data then we used label encoder to convert the strings to numerical values then we used feature scaling and created an endpoint to interact with other services and we created lambda function to trigger the ml model and we created rest API to create the website. This whole thing was secured with the architecture.

Figure 5: The Block diagram of the Churn Model

Our original goals for this project were to build the architecture that provides better security to secure a web application. We create multiple tiers. For load balancing we create a separate subnet for publicly accessing servers we create another subnet for databases, and we create a backup of EC2 instances as snapshots with the help of AWS lambda we monitor a website with AWS cloud watch. This helps to secure the website if anyone of the services compromised while an attacker attacks the website, he cannot access the other services which are there in other subnets. Still, if any attack happening an SMS alert will be sent to the admin. To secure the admin access we use a VPN for admin.
flask網頁建設主題
By: Steven Wang
Tags: Flask

Gravatar - Globally Recognized Avatars

Gravatar images may be requested just like a normal image, using an IMG tag. To get an image specific to a user, you…
Fire-Up Your Backend With FastApi Starlette And Uvicorn
By: Ronald Abreu
Tags: Asynchronous, Fastapi, Django, Asyncawait, Flask

Photo by Bill Jelen on Unsplash

“Knock, knock.”

“Who’s there?”

very long pause….

“-Rails.”

Ever arrived at a web application only to navigate away because the content you were looking for didn’t load soon enough?

According to TechEmpower, a platform that compares the performance of a wide range of web application frameworks using community-contributed test implementations. Rails performance - making it to place 363rd on the list - is way behind other popular backend framework alternatives like Flask coming in at number 360th or Django at 345th.

But there is a new player in town called FastApi leaving them all in the dust.

FastApi is a relatively new Python framework that enables you to rapidly develop an API or backend for your web or mobile application.

This one Framework is gaining popularity among Python developers because of its speed and usability.

Surpassing both Flask and Django’s performance, FastApi makes it to the 228th spot on TechEmpower’s list.

So what is FastApi bringing to the table that makes it that much faster?

FastApi is built on a Python framework called Starlette which is a lightweight ASGI framework/toolkit, which is itself built on Uvicorn.

Ideal for building high performance asyncio services with seriously impressive performance.

But the key to performance here is ASGI.

ASGI or Asynchronous Server Gateway Interface is a standard interface between async-capable Python web servers, frameworks, and applications.

It is essentially an asynchronous model for Python server communication.

Providing Python users with a framework that actually supports async and await.

When Python was created in the early 90’s it wasn’t designed with async support in mind because we simply didn’t have the computing power for it.

Without going into too much technical details, Pythons async problem lies in its use of a Global Interpreter Lock.

The global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once.

This lock is necessary mainly because CPython’s memory management is not thread-safe. -PythonWiki

Python executes multi-threads by context switching even for idle processes creating a massive computing overhead.

Adding async support for Python didn’t come until asyncio was introduced with the Python 3.4 release in March, 2019.

And while Django and Flask both have a large following and provide very useful database tools, they both suffer when it comes to async and await support.

With Django claiming ASGI support while not yet supporting the await feature. Basically allowing you to do some asynchronous task but not being able to wait for the task to be done. And it’s the same thing with Flask.

This is where FastApi takes the cake! With its use of Uvicorn’s lightning-fast ASGI server implementation. Providing support for HTTP/2 and WebSockets, which cannot be handled by WSGI.
Deploy flask app with Nginx using Gunicorn less than a minute
By: Behrad Kazemi
Tags: Deploy, Bash, Nginx, Gunicorn, Flask

Deploy flask app with Nginx using Gunicorn less than a minute Behrad Kazemi ·Nov 14, 2020

Many thanks to Rahul Nayak and Tasnuva Zaman for publishing an awesome article about deploying a flask app using Nginx and Gunicorn.

But we need to do lots of works for deploying each time we commit into our git repository and our time is gold!

so we need to automate the job with bunch of scripts to do all the stuffs for us.

E asy way…

I just automated all the command into couple of bashes:

https://github.com/behrad-kzm/EasyDeployer

All you have to do is copy the Runner folder and paste it into your project directory.

Project structure:

Your project must have these files:
EasyDeployer steps
By: Behrad Kazemi
Tags: Deploy, Bash, Nginx, Gunicorn, Flask

Setting up app.service and creating app.sock into your project.

#!/bin/bash echo $'

-----Creating systemd unit file-----

'

cd ../../ if [ /etc/systemd/system/app.service ];

then

echo $'

-----Removing existing app.service-----

';

sudo rm /etc/systemd/system/app.service;

fi echo $'

-----Creating app.service-----

' var_username=$USER echo "Created gunicorn with $1 worker processes to start"

var_workers=$1 DIR=$PWD systemd_path="/etc/systemd/system/app.service"

systemd_content=$'[Unit]

# specifies metadata and dependencies

Description=Gunicorn instance to serve project

After=network.target

# tells the init system to only start this after the networking target has been reached

# We will give our regular user account ownership of the process since it owns all of the relevant files

[Service]

# Service specify the user and group under which our process will run.

User='$var_username$'

# give group ownership to the www-data group so that Nginx can communicate easily with the Gunicorn processes.

Group=www-data

# Well then map out the working directory and set the PATH environmental variable so that the init system knows where our the executables for the process are located (within our virtual environment).

WorkingDirectory='$DIR$'

Environment="PATH='$DIR$'/venv/bin"

# Well then specify the commanded to start the service

ExecStart='$DIR$'/venv/bin/gunicorn --workers '$var_workers$' --bind unix:app.sock -m 007 wsgi:app

# This will tell systemd what to link this service to if we enable it to start at boot. We want this service to start when the regular multi-user system is up and running:

[Install]

WantedBy=multi-user.target'

echo "$systemd_content" > $systemd_path systemctl daemon-reload

echo $'

-----Starting app-----

'

sudo systemctl start app

sudo systemctl enable app echo $'

-----Done-----

'

cd Runner/scripts
OCR using Pytesseract + Flask Server and base64 Image String in Python
By: Sidhartha Mallick
Tags: Ocr Tesseract, Flask Restful, Optical Character Recogn, Ocr, Flask

Create a basic Flask Server . Create a virtual environment using env. Install dependencies like opencv-python and Pytesseract using pip/pip3. Add the OCR function to your code. Game Onnn !!

Define Flask path parameters:

export FLASK_ENV=development

export FLASK_APP=app.py

Create Environment using venv :

python3 -m venv venv

. venv/bin/activate

Define the OCR function in your app.py/server.py/index.py :

# [data] parameter is a dictionary with a key "photo" which contains # the base64 image string def ocr(data):

with open("UploadFiles/ss.jpeg", "wb") as fh:

fh.write(base64.b64decode(data["photo"]))

img = cv2.imread("UploadFiles/ss.jpeg")

custom_config = r'--oem 3 --psm 6'

text = pytesseract.image_to_string(img, config=custom_config)

return text

Define the API endpoint

@app.route('/ocr', methods=['POST'])

def ExtractTextFromOcr():

data = json.loads(request.data)

result = ocr(data)

print(result)

return result

Dev Dependencies :

flask

opencv-python

Pytesseract

python-dotenv

Use pip install to install all the dependencies

pip install -r requirements.txt

Checkout the Github repository : Link. Follow the readme well.

Note: Don’t use Heroku or similar hosting platforms for tesseract based applications. Better use, AWS or Google Cloud.

!! Happy Coding !!
Connecting Flask with Node.js.
By: Dhanam Parekh
Tags: Programming, JavaScript, Nodejs, Flask, Machine Learning

Photo by Kevin Ku on Unsplash

Connecting Flask with Node.js.

Introduction:

There are various reasons which require building a connection between Node.js and Flask. Recently, I did it in order to integrate my Machine Learning model implemented in Python with my website which uses Node.js as a backend. The procedure is quite simple. Let’s dive in without further ado.

Step 1: Build Flask Server

We first need to build the Flask server which will be listening to data sent from Node.js.

We are now running our server on port 5000 on our local machine. Additionally, we have created a simple route that will return a string back when a get request is sent from Node.js to the /flask endpoint.

Step 2: Build the Node.js Backend

In this step, we will lay out our backend using Node.js and Express.js. Express.js is a popular web framework used to build API’s.

We will use the request library which can be installed using npm. The request library is the most simple library designed to make http calls.

As we can see in the code, when a user visits the /home endpoint, a get request is sent to http://127.0.0.1:5000/flask which is our endpoint for the flask server. We will receive the string “Flask Server” as a response back from the Flask.

Result:

It’s time to check whether we are successful in getting a response from our Flask server. We can check using Postman which is a tool used to design and test API’s.

Screenshot by author

We can see that we receive the string “Flask Server”. Hence we are successful in creating the connection.

Conclusion:

As discussed above, there are various use-cases where connecting Node.js and Flask is useful. The most common use is when we need to add Machine Learning to our website since it is easier to implement Machine Learning in Python (due to super helpful libraries) and connect it to Node.js using Flask, rather than implementing it all together in Node.js.
Python Web Flask — 如何透過Form取得資料. 使用POST方式並且使用session，來製作login與logout功能。
By: Sean Yeh
Tags: Forms, Sessions, Python3, Flask, Python

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
SafeZone: A web application mapping COVID and disaster related information for your state.
By: Christian Mosley
Tags: Covid 19, Flask Framework, Disaster Response, API, Flask

The premise is simple, when disaster strikes, what is your plan? Do you even have a plan? Does your plan account for different types of disasters? With SafeZone, you will feel safer knowing you have a plan of action when the worst moments strike.

Recently, I worked with a team to build a web app, with it’s goal being to deliver ongoing disaster related information to the user for their state of residence in the US. Along with current disaster related information, the app would also deliver 7 day moving averages for COVID positivity rates.

The scope of the project could potentially be very large with thousands of cities across the US, so we wanted to deliver an MVP that would start at the state level, to eventually be expanded further to major cities across the United States.

First, we needed to find a way to gather disaster data from a reliable and timely source. We came upon an API from FEMA that served this purpose quite nicely. It had historical disaster related data as well as current ongoing disasters. Our team wrote a script that would pull the required disaster data and we linked that data to a database to be extracted later.

Next, we looked for a source that had COVID related data. We settled on an API with the CDC that provided the 7 day moving average data we used. The next portion of our CDC data was to develop a model that could predict increases in the 7 day moving average 1 month and 2 months out. Without any prior seasonal lagging periods for COVID, we used previous winter flu rates as a substitute to map our positivity increases. With the flu data and current COVID data in hand, we built a simple SARIMA time series model that would forecast out 1 and 2 month ahead of time. Now we were ready to build that app.

We debated which framework to use to get our app displayed, we had narrowed down our choices to making a simple Streamlit app, or going with a more robust solution in Flask. The flask framework won out mainly because we wanted to expand our skillset and eventually have the styling capabilities to make a beautiful app.

The first iteration produced the screenshots below, where we had a form field that would take in the state the user wanted info on and a simple team page to showcase how handsome we were.

After a long night of debugging some pesky routing issues in flask, here is a demo of version one of our app SafeZone.

We learned a lot building this application, and could definitely expand upon the app by refining our data models for COVID predictions, adding in more granular search capabilities and getting the user a more ready make plan of action to take when disaster strikes.
flask相關建設主題
By: Steven Wang
Tags: Flask

flask相關建設主題

使用Security Helpers的兩個方法

generate_oasswird_hash

check_password_hash

python command

%python

from werkzeug.security import generate_password_hash, check_password_hash

generate_password_hash(‘admin’) ‘加密

每次hash都不會一樣

b=generate_password_hash(‘admin’)

check_password_hash(b, ‘admin’) ‘核對密碼 返回true/false

command python檢查(完整的啟動python command)

python>>>

>>> from twittor import db, create_app

>>> from twittor.models import User

>>> app = create_app() ‘實體化

>>> app.app_context().push() ‘push方法

>>> u = User(username=’admin’, email=’admin@admin.com’) ‘一個實例

>>> u.set_password(‘admin’) ’設定hash密碼

>>> u

id=None, username=admin, email=admin@admin.com,password, password_hashpbkdf2:sha256:150000$A1X5TSLh$bbcae5a7b0321afc7df1a524cb909a57dd664350f0685ac21a6199a9520f63f1

>>> db.session.add(u)

>>> db.session.commit() ‘新增入資料庫

>>> User.query.all() ‘有資料

[id=1, username=admin, email=admin@admin.com,password, password_hashpbkdf2:sha256:150000$A1X5TSLh$bbcae5a7b0321afc7df1a524cb909a57dd664350f0685ac21a6199a9520f63f1]

>>> User.query.filter_by(username=’admin’) ’有東西

<flask_sqlalchemy.BaseQuery object at 0x10c45a2b0>

>>> User.query.filter_by(username=’admin’).first() ‘first()方法

id=1, username=admin, email=admin@admin.com,password, password_hashpbkdf2:sha256:150000$A1X5TSLh$bbcae5a7b0321afc7df1a524cb909a57dd664350f0685ac21a6199a9520f63f1

>>> User.query.filter_by(username=’adminn’).first() ‘沒有adminn返回None

移除csrf警吿

FlaskWTFDeprecationWarning: “csrf_enabled” is deprecated and will be removed in 1.0. Pass meta={‘csrf’: False} instead.

移除csrf_enabled=False

新增class Meta

forms.py / class Meta

Flask_Login用於用戶session的管理

已經登錄過 要被記起來

頁面只允許login的用戶去訪問

pip install flask_login

LoginManager

from flask_login import LoginManager '引入flask_login LoginManager 類

別

login_manager = LoginManager() ‘定義login為LoginManager的一個實例login_manager.init_app(app) 'login與app進行關聯 初始化

UserMixin提供用戶session的幾個基本方法

is_activate

is_authenticated

is_anonymous

get_id

改造Models / User 將 UserMixin當作父類提供給User繼承，這樣User就會有Mixin的以上方法

models放置user_loader callback回調函數

This callback is used to reload the user object from the user ID stored in the session（要讓app login方法根據id找到用戶）

login_manager內user_loader方法裝飾def load_user

＠login_manager.user_loader

def load_user(id)

(session存儲的類型是string要改成int)

login_user

>就可以開始在route.py使用login_user方法，使用login_user(user) (flask_login)的方法去紀錄當前已經通過驗證的用戶

設定config.py/SECERT KEY

current_user

current_user 當前的用戶flask_login的current_user方法

is_authenticated 被認證過

如果被認證過，就不需要再登入

redirect(url_for(‘index’))

logout 登出

route.py/from flask_login import logout_user

route.py

def logout()

logout_user()

templates folder/base.html

base.html

{% if current_user.is_anonymous %}

UserMixin內有is_anonymous方法 是否匿名，沒login就是匿名

強制用戶登錄 沒有登錄不給看＠login_required

from flask_login import login_required

未登錄則進入此畫面

以下修改__init__.py，引導頁面到login輸入帳密

跳出登錄頁面輸入正確後，回到原本要進入的頁面next

觀察login?next=OOOXXX，登錄後就會回到原本要進入的頁面（就是OOOXXX）

取出next所帶參數

from flask import request

next_page = request.args.get(‘next’)

轉入

if next_page:

return redirect(next_page)
The Udacity Data Science Nanodegree — What do you actually learn about Data Science?
By: Joseph Alan Epstein
Tags: Udacity Nanodegree, Data Pipeline, Recommendation System, Flask, Data Science

Recommendation Systems

Without getting too involved with the code, I wanted to spend some time just discussing the general concepts that were introduced in this course.

What’s the best way to recommend content?

Unfortunately, there’s no straightforward answer to this question, but if we know the type of content that we’re working with, and know if we have data on user interactions, then we’re good to go. For instance, if you were running a website for a luxury goods, then the safe bet is to use a Knowledge-based recommendation system. A Knowledge-based recommendation is simply one that ranks the content based on a value (like a price range), and provides every sample that satisfies the filter. This would also be appropriate in the case of recommending an article; if we were recommending to a user that had never been on the site before, then they should just be recommended the most popular article.

I heard Collaborative Filtering is the best technique

Collaborative Filtering really just means keeping a matrix that has users as its rows, and articles as the columns, then calculating for similarity among the rows. How you attempt to calculate similarity, will determine how good the technique is. You could use a simple dot product, or you could factorize the matrix with T-SNE, and calculate similarity by Euclidean Distance. Content-based techniques have their place, and can be done quickly with something like Doc2Vec. Also, a Content-based technique is not limited by the amount of data that is collected, whereas a Collaborative Filtering model may not work as well without enough data. There are other techniques as well, to fill in the gaps (predict).

FunkSVD is pretty sweet

FunkSVD is one potential solution to this “cold start” problem. Because gradient descent always makes our lives easier. Essentially, you can decompose a user-article matrix, fill in random values, iterating and learning values for the previously missing entries. You can see the documentation here.
資料庫與flask
By: Steven Wang
Tags: Flask

Flask-SQLAlchemy - Flask-SQLAlchemy Documentation (2.x)

See the SQLAlchemy documentation to learn how to work with the ORM in depth. The following documentation is a brief…
Caching result of a method in Python
By: Anurag Kumar
Tags: Django, Caching, Django Rest Framework, Flask, Python

Recently I was working on adding a new feature to an existing legacy code. But then while working on it, I found a sweet problem which was quite new for me.

def get_obj():

model_obj = model() # Some large database query

return model_obj



def get_obj_value(self):

obj = self.get_obj()

return obj



def get_obj_value_dup(self):

obj = self.get_obj()

return obj

As we can see I have a method get_obj() which does some database query and returns that. This method was already there and I just had to use it in my separate methods, but soon I realized that this method get_obj() was being used in multiple places and it was always making database query which is computationally very costly. Thus the idea of caching the return value of the method came to my mind.

Currently, in the above code snippet, we can see that the return value of the method is computed always. To reduce that I used a custom memoize decorator which would cache the result of a method with a single self argument as property and its result will persist as long as the instance does.

def memoize(function):

memo = {}



def wrapper(*args):

if args in memo:

return memo[args]

else:

rv = function(*args)

memo[args] = rv

return rv



return wrapper



@memoize

def get_obj():

model_obj = model()

return model_obj



def get_obj_value(self):

obj = self.get_obj()

return obj def get_obj_value_dup(self):

obj = self.get_obj()

return obj

Here we can see that memorize stores its cached result in the memo dictionary. Now if we go inside the wrapper function, if args in memo-> here is checks that if the cached results already exist then return that without going inside the main function, else-> go inside the function, compute and then store the result and return the existing result.

Alternatively, another memoization decorator with a limit on the cache size can be implemented when you do not want your memory to be full if a single instance is caching quite big enough.

Also, we can use the python Funtool library's cached_property .

from functools import cached_property



@cached_property

def get_obj():

model_obj = model()

return model_obj

Thus, we could see how the caching result of a method helped me in this case. But this power should be used wisely and not followed blindly everywhere.

There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton

Sometimes we need to work a little with a model instance and where we need to change the object and send it to the response. Django provides the refresh_from_db() method to reload an object from the database. Refreshing the object from the database all model fields and relationships are cleaned out and non-deferred fields are reloaded, but the cached method is not a model field and the value is still stored in self.__dict__.
【程式學習】 Flask網路教學課程介紹及基礎知識_給CS50x_week8的補充資料(1)
By: 康凱原 Kai
Tags: 程式設計, 電腦科學, Cs50, Flask, 網站開發

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
【程式學習】哈佛CS50x學習筆記_第8週最後作業
By: 康凱原 Kai
Tags: 程式設計, 電腦科學, Cs50, Flask, 網站開發

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Twitter Bot or Not
By: Chris Doenlen
Tags: Twitter, Twitterbots, Flask, Data Science, Machine Learning

Twitter Bot or Not

Photo by Ray Hennessy on Unsplash

Whether you’re on Twitter or stay away from social media altogether, these platforms affect us all — from shaping public discourse to entertainment to spreading information.

The existence of bots on these platforms has gained a lot of attention in recent years, and yet many people are still unaware of or misunderstand their presence and purpose on platforms like Twitter.

And so it’s important that we start with a simple working definition of a bot:

A Twitter bot is a software bot that controls a Twitter account via the Twitter API. It may autonomously perform actions like tweeting, retweeting, liking, following, unfollowing, or direct messaging other users.

Bots are designed for a variety of purposes: they can be creative, helpful, informative, and even funny.

There are, of course, more nefarious bots — bots that can spread misinformation or scam other users. The presence of these bots can degrade our experience on these platforms and worse: our trust in one another.

Instead of bucketing all bots into good or bad, I think developing bot awareness is key to preserving social trust and the integrity of these platforms. And so with that in mind, I wanted to create a tool that could help Twitter users and spectators alike become more bot aware: Twitter Bot or Not.

Users can enter in any Twitter handle and see the probability of that account being a bot based on a dozen or so account-level features (more on that to come). These predictions are intended to provide the user with peace of mind with regards to who they’re following or interacting with.

I developed a supervised machine learning classification model using Python, the sklearn library, and XGBoost, and then built a simple app using Flask that I deployed on Heroku. In this post, I’ll walk through a few of the steps that went into developing the model and the app. All of the code and notebooks can be found on my GitHub.
Talking to Python from Javascript: Flask and the fetch API
By: Daniel Ellis
Tags: JavaScript, Fetch, Towards Data Science, Flask, Python

Creating a Flask app

We start by building a repository containing an empty templates folder and an app.py file.

App.py

Our app.py file contains the data required to create a web interface. To do this we use the flask ( pip install flask ) python library. For this we can use the following template:

######## imports ##########

from flask import Flask, jsonify, request, render_template

app = Flask(__name__) #############################

# Additional code goes here #

############################# ######### run app #########

app.run(debug=True)

Here we start by importing the required functions, the app structure and the run command to start the app.

Index.html

Having defined our flask app, we now need to create a template webpage. This can be done by placing the file index.html within the templates directory.

<body>

<h1> Python Fetch Example</h1>

<p id='embed'>{{embed}}</p> <p id='mylog'/>

<body>

Since we are using this as a template we can use a react-style replacement syntax for certain keywords. In this instance {{embed}} is to be replaced by the embed_example string in the snippet below.

'/')

def home_page():

example_embed='This string is from python'

return render_template('index.html', embed=example_embed) @app .route(def home_page():example_embed='This string is from python'return render_template('index.html', embed=example_embed)

This defines the code which runs when the home page of the flask app is reached and needs to be added between the imports and the app.run() lines within app.py .

Running the app
Why You Should Stop Using Flask and Start Using FastAPI
By: Fahmi Nurfikri
Tags: Programming, Python, Flask, Data Science, Machine Learning

Why You Should Stop Using Flask and Start Using FastAPI

Photo by Pankaj Patel on Unsplash

When it comes to machine learning production, usually we’ll wrap a model into a rest API. Because making machine learning APIs doesn’t really require complex things — it only requires the predict() function — we usually only use a simple framework. And the framework we usually use is Flask.

Don’t get me wrong: Flask is good, but it’s in the past. One reason Flask is widely used is that in the past, not many people deployed models as real-time production APIs. For some people, Flask is good enough because it’s popular, minimal, and written in Python.

As time’s gone by, the production of machine learning, as a field, has matured. However, as this field has matured, features that were originally just nice to have become essential. And that’s a feature that Flask doesn’t have, so sometimes we have to use third-party dependencies, and sometimes the documentation isn’t too clear.

This is what made me look for other alternatives to create real-time production APIs. In the end, I found a web framework called FastAPI. FastAPI is a relatively new web framework for Python but is powerful and enjoyable to use. Here are some reasons why you should start using FastAPI.
Building Rest API with MongoDB in Flask by using JWT authentication 🔄
Tags: API, Mongodb, Flask, Python, Software Development

Now let’s finish the native.py file📜

You can see I’m importing two more libraries pymongo & json.

Since we are working with MongoDB we have to use pymongo. And json for Serialize obj as a JSON and to return response in JSON format.

You could see my DB connection in Try and Catch Block. In native.py I’m using MongoDB localhost(native driver).

@app.route() is for defining the route for GET, POST, PATCH & DELETE.

You can see I’m using @jwt_required() before def create():, def update(name):, def delete(name):.

So while accessing these endpoints in postman u’ll get an err as:

Means that you have to create a header of JSON content-type and add an authentication header using the access token what you get.

GET REQUEST:

You can see I’m getting JSON values from my MongoDB Localhost.

POST REQUEST:

For posting a value you have to select POST and enter the post route and enter the data in the BODY tab FORM_DATA.

You can see the error I’m getting. This is because we have required @jwt_required() before the POST route.

Now, You have to create a header for content-type: application/json and switch to BODY → raw and enter the user’s data.

NOTE : Change the route to http://127.0.0.1:3030/auth

You can see my access_token. Copy the token which you get without quotes. Then move to Header create a new key Authorization and add value as JWT and your token.

And now You can add/post data through form-data. It’ll get added to your local MongoDB.
Deploy Interactive Real-Time Data Visualizations on Flask With Bokeh
By: Michael Bagley
Tags: Database, Data Visualization, Bokeh, Flask, Python

Part One

The first step is to do pip install bokeh and pip install Flask to get the Bokeh library and Flask library installed to your Python instance. Create a file called app.py and start with the following code:

The variable source is used to represent data in a way that is standardized for Bokeh elements. We will pass our data into that object, which is fed to the Bokeh figure. It is structured as an object, mapping keys to an array of values. We will later see how we can directly access and manipulate this using CustomJS .

Next, fig represents a Bokeh visual component. The tooltips parameter sets what is displayed in the display box that is shown when you hover over a point in your visualization. The tuples of this array are structured as ("NAME TO DISPLAY", "@COLUMN_NAME_IN_SOURCE" . To edit how large individual points on the graph appear, you can edit the size parameter in fig.circle() . Keep the x , y , and color parameters the same because we will see how those can be conditionally changed later.

The axis_label variables control what is displayed on the X-axis and Y-axis of the visualization. In our case, the X-axis will measure the IMDB rating of a movie and the Y-axis will measure the Rotten Tomatoes rating. We will later see that (obviously) there is a positive correlation between the two.

Now we can implement the following code to pass some data into our figure and display it in our browser:

Until Part two, we will be using an array of five example dictionaries featuring various movie-related properties. We are eventually going to be retrieving 3,000 real-time records from EasyBase.

The properties being set in source.data are Bokeh’s reference as to where in the graph an element should be displayed, along with how it should appear visually. As stated before, the structure of this variable is a dictionary mapping all of our attributes to a corresponding array. For this reason, we are using the inline array construction syntax to grab and pull each property from our data into its array.

We can see where these elements are used in our Bokeh figure: x , y , and color are passed into the fig.circle() method, and title and genre are passed into the tooltip (we will use released , imdbvotes , and genre later). Feel free to alter the values in each array. For example, if you want the color of dots to correspond to its genre, color = ["#FF9900" for d in currMovies] is where you would do that, or perhaps color = ["#008800" if d['genre'] == "drama" else "#FF9900" for d in curMovies] .

Last, output_file points to where you want your later figures to be saved. show(fig) saves the figure at this location and opens it in your browser.

Run this file and you will be presented with:
Simple Flask Pagination
Tags: Programming, API, Flask, Python, Software Development

Now the Pagination Part

3. Modify the view to cater to pagination.

ROWS_PER_PAGE = 5 @app.route('/colors')

@login_required

def colors():

# Set the pagination configuration

page = request.args.get('page', 1, type=int)



colors = Color.query.paginate(page=page, per_page=ROWS_PER_PAGE) return render_template('colors/all_colors.html', colors=colors)

Results are paginated using the paginate function of Flask SQLAlchemy with any number of arguments as desired. The result of calling the paginate() function is a Pagination Object, which has many methods that can help you achieve your desired result. You can read more about this in the documentation.

4. Modify the display template

To display the items, you have to call the .items method of the colors pagination object defined from the back end.

<div class="table-responsive">

<table class="table table-sm table-borderless mb-0">

<thead class="thead-dark">

<tr>

<th>S/N</th>

<th>Color Name</th>

<th>Date Created</th>

<th>Actions</th>

</tr>

</thead>

<tbody>

{% for color in colors.items %}

<tr>

<th scope="row">{{ loop.index }}</th>

<td>{{ color.name }}</td>

<td>{{ color.created_at }}</td>

</tr>

{% endfor %}

</tbody>

</table>

</div>

Only five items are returned because we set ROWS_PER_PAGE = 5 .

5. Add the pagination button views for navigating through pages.

<!-- Pagination Links-->

<div class="text-right">

<a href="{{ url_for('colors', page=colors.prev_num) }}"

class="btn btn-outline-dark

{% if colors.page == 1 %}disabled{% endif %}">

«

</a> <!-- Loop through the number of pages to display a link for each-->

{% for page_num in colors.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %} {% if page_num %}

<!-- Check for the active page and set the link to "Active"-->

{% if colors.page == page_num %}

<a href="{{ url_for('colors', page=page_num) }}"

class="btn btn-dark">

{{ page_num }}

</a>

{% else %}

<a href="{{ url_for('colors', page=page_num) }}"

class="btn btn-outline-dark">

{{ page_num }}

</a>

{% endif %}

{% else %}

...

{% endif %}

{% endfor %} <a href="{{ url_for('colors', page=colors.next_num) }}"

class="btn btn-outline-dark

{% if colors.page == colors.pages %}disabled{% endif %}">

»

</a>

</div>

<p class="text-right mt-3">

Showing page {{ colors.page }} of {{ colors.pages }}

</p>

And here is your result:
Sabrina the Teenage Witch
By: Riley Lopez
Tags: Witchcraft, Writing, Sabrina The Teenage Witch, Halloween

Back in 1962, the character Sabrina Spellman first appeared in the Archie comics, more specifically, Archie’s Madhouse, and was later adapted into its own spin off. The premise of the series is that Sabrina Spellman is just your average American teenage girl, except for the fact that she is half witch, half human (her dad was a witch and her mom was a human). She lives with her two aunts, Hilda and Zelda Spellman, who are both witches, in the town of Greendale, located somewhere near the other fictional town of Riverdale which is the home of Archie Andrews, the main character from the original Archie Comics. Also living with the three women is the family pet Salem. Salem was a witch who was been turned into a cat a punishment for several world domination attempts. Sabrina’s primary love interest is a human boy named Harvey Kinkle, who like most of the humans in Sabrina’s life, have no idea that she is a witch. Since the creation of the fictional universe, several television studios and networks have rendered their own version of Sabrina Spellman and her adventures as a witch.

The first show following Sabrina’s adventures came out in 1996, titled Sabrina the Teenage Witch, starring Melissa Joan Hart as Sabrina Spellman. This show follows the comic pretty closely compared to its successors. One thing the producers of the show changed was when Sabrina finds out she is a witch. In the comic Sabrina has always known she is a witch, as revealed in the “Sabria That Cute Little Witch” storyline. In the show, however, she finds out in the first episode, on her sixteenth birthday, and her and her aunts live in a fiction suburb of Boston instead of Greendale. The show was on for a total of seven seasons airing from 1996 to 2003, following Sabrina’s life in high school, hiding the fact that she’s a witch, the when she goes to college and eventually gets married to Harvey Kinkle.

The storyline of Sabrina had many spin offs after 2003, none of which as popular, or successful as Sabrina the Teenage Witch, until December of 2017, when Netflix announced they were creating their own world of Sabrina Spellman. The Chilling Adventures of Sabrina takes a darker look at the world of witches and warlocks. All the witches are apart of a cult-like religion called The Church of Night.
Meeting Angelika, Sailing Yacht A, and Leaving Rhodes
By: Yvette Graham
Tags: Halloween, Greece, Rhodes, Sailing Yacht A, Over 60s Womens Travel

I was still looking at either going to Turkey or Costa Rica to try to get into the States after the 2 weeks spent in either of those countries, but I hadn’t quite decided yet, but fate seemed determined to lend a hand. I was planning on going to Costa Rica with a Norwegian lady that I had met on-line and staying for 2 weeks at a home exchange place that I had lined up when suddenly I met an English guy in Turkey on-line. He wasn’t bad and was my age and he called me, we talked for about 2 hours and got on great, he was just across the water in Fetiye, Turkey, about 90 mins boat ride, however the boats weren’t running now due to the dreaded Covid, which was starting to annoy me now. I thought about my options, my next months rent was due on the 3rd November and it was a few days away, which meant I would have to stay in Rhodes for at least another month, virtually locked up with nothing to do as everything was now closed now, and Angelika was leaving for German too, or I could leave now and meet this guy John and be in Turkey, where I was thinking of going anyway, so really there was no contest.

Flights proved to be a problem, I had to take 4 flights over the course of 24 hours to get to Dalaman, (normally a quick boat trip grrr), but there was no other option really, I had a refund that I could use to get to Athens and the other flights weren’t too expensive, only 17 euro to get from Istanbul to Dalaman, with luggage!!! Seriously! I had to go via Romania, which was madness. I booked a villa via home exchange for a week as I didn’t want to have to stay with or be obligated to this man as I didn’t know him, although everything seemed perfect on paper!!

So on November 3rd, Annie my lovely new vegan friend gave me a lift to the airport at 8am, I gave her my bike in exchange! And I set of for Athens, then Romania and arrived at Istanbul around midnight, not long flights but I had an 8 hour wait in Athens airport and had to wait 7 hours overnight in Istanbul airport for my flight to Dalaman the next morning at 8am. Super tired but very excited to get to Turkey and meet this man. It seemed like fate….not that I was really looking for a man, but one never knows…
Mom Turns Her Baby Into A Zombie For Halloween Photoshoot And It’s Terrifying
By: Wonder Earth
Tags: Halloween, Baby, Photoshoot, Zombies, Mom

Mom Turns Her Baby Into A Zombie For Halloween Photoshoot And It’s Terrifying Halloween has to be one of the most popular times of the year. I think deep down inside we all want to pretend to be something we aren’t for a short period of time. That’s what makes Halloween so special. We always seem to navigate to the dark and scary part of our psyche and the creations that are made every single year never fail to impress. Well this year Tiffany Renfroe, a photographer and a nurse from Dothan Alabama, might have just set the bar. This is her first photoshoot of her baby Oakley utilizing some of her talented friends and family to make her vision come to reality. A little forewarning though, no babies or zombies were harmed in this photoshoot. That’s right… ZOMBIES! Take a look at this incredible zombie inspired photoshoot just in time for Halloween.
I had no idea where you were going with this until the electrocution.
By: K.C. Knouse
Tags: Halloween, Short Story, Humor, Fiction, Horror

I had no idea where you were going with this until the electrocution. Aha! You had me believing that the electrocution had cured Brian's malady then — vintage Stephen.
Halloween is coming up soon but that won’t be the only spooky thing coming our way.
By: Amanda Swanson
Tags: Covid 19, Spooky, Halloween

As we approach the middle of October, most of us would typically be obsessing over what costume to wear or to match with our best friends, which parties to attend or what movies to watch that night while eating every piece of Halloween candy you can get your hands on. But this year, as we all know, is filled with Covid and masks (not the fun kind). While being away from friends and family, here are some of the best ways to celebrate your favorite scary holiday while keeping your healthy distance.

Have a dress up contest on Zoom with your friends: This one is self explanatory but just as fun if you get in character. By having your friends on the same call is the next best thing to not going door to door with them Send / drop off Halloween candy bags: This gives Trick or Treat a whole new meaning, you can decide to be sweet and fill little bags with candies and special things for them or you can do something else. Like fill the little bag with the Bean Boozled jellybeans and just comepletely alter their tastebuds for a couple hours. Have a movie party FaceTime call: Kick back, make your favorite snack and hop on that call, Halloweentown is calling your name!

This Halloween and all of the other holidays coming up will be ones to remember so a word of advice: stay safe, wear your mask, and be grateful that we are still able to communicate and have some sort of contact with our loved ones.
The Urban Legend of the Corpse Bride
By: Tristan Clyde - A Pseudonym
Tags: Halloween, Legend, Urban Legends, Death, Creepy

There are two very well known urban legend revolving around the theme of a corpse bride. The first one occurred in Mexico where a woman owned a bridal shop with a very life like mannequin displayed at her window, because the mannequin was so life like and wearing a wedding dress, rumors spread that it was actually the body of her daughter who had passed away on her wedding day. That story was proven to be untrue, however, a story that is true is the story of Carl Tanzler, His Wife passed away in 1931 and he continuously injected her with formaldehyde in order to preserve her body and supposedly did some unspeakable acts to her corpse.
Have A Look At These 8 Houses And Their Awesome Halloween Decorations
By: Moazam Nabi
Tags: Halloween Costumes, Halloween, Halloween Decorations

With Halloween just around the corner, we thought we’d take a look at some of the best Halloween houses we could find. Here are 8 houses whose Halloween decorations are pretty creepy, but pretty amazing at the same time.

1. Venture into this house’s front yard and you’ll be greeted by all the Halloween favourites, including skeletons, ghosts and pumpkins

via Twistedsifter.com

2. This house’s patio features an assortment of classic horror film characters, such as Hellraiser’s Pinhead and Nightmare on Elm Street’s Freddy Krueger — approach if you dare

via Syracuse.com

3. A creepy home basked in a somewhat disturbing green light, with an eerie orange glow coming from its highest window…would you want to live here?

via Pinterest.com

4. Not many would dare to venture into this yard of terrors late at night…especially with hands poking up out of the ground

5. Not the creepiest decor, but a lot of effort certainly went into decorating this house for Halloween

via Parade.com

6. A house with very creative decorations, featuring ghouls and creeps escaping from boarded-up windows and falling to the ground

via Wuwm.com

7. A simple and effective use of huge cobwebs gives this otherwise normal house a rather creepy and abandoned feel

via Youngprogress.com

8. This brilliantly decorated house comes alive with lights galore when the sun goes down