fabiochiu/medium-articles huggingface dataset:
När städer rör sig snabbare mot klimatneutralitet än sina nationer
By: Viable Cities
Tags: Smart Cities, Climate Action, Cities, Sustainability, Climate Change

— -

When cities move faster towards climate neutrality than their nations

During EU Week of Regions & Cities, Covenants of Mayors gathered a wide range of cities and regions in the seminar Governance models for climate neutrality, which showed that cities and regions are moving faster towards climate change than nations.

Author: Lena Holmberg, portfolio strategist Viable Cities

Warsaw Mayor Rafal Trzaskowski talked about how many of Poland’s cities are gathering strength on their own to become climate neutral. They do not receive direct support from the state in this matter but are rather opposed. This shows both what cities can achieve if they decide to become climate neutral, but also the importance of initiatives at EU level for European cities, such as 100 Climate Neutral Cities by 2030 — by and for citizens.

Turku, Finland.

The municipality of Turku, Finland, was recently named the best medium-sized climate city by the Covenant of Mayors. They aim to become climate neutral as early as 2029 and for several years now have had an initiative they call 1.5-degree lifestyle which has been successful in clarifying what it means to live climate-smart. Now before Christmas, there is a competition where citizens can submit videos on this theme, as part of civic involvement and visibility. Also, they have developed a method to prioritize which areas are most important to focus on in terms of creating a circular economy, something that many other cities demand.

The city of Leuven was recently awarded the European Capital of Innovation 2020 award. Their mayor, Mohamed Ridouani, presented how they have been innovative in terms of governing the city by developing a completely new organizational form for collaboration on climate transition, which also has its own budget: Leuven2030. At Transition Lab Forum 4, the leader of Leuven2030, Katrien Rycken, talked about what they have achieved so far and the plans for the future. It would have been exciting with a (virtual) study visit to learn more about this, especially in terms of the interaction with the regular municipal administration.

Last out of the session was the Vice President of the Loire region, Charles Fournier, who presented how they have mobilized banks, companies and citizens to get investments for their climate transition. There, they have invested heavily in involving young people in their work, but have also set up a one-stop-shop to be able to connect with financiers such as the European Investment Bank.

Everyone on the panel was asked how it was possible to link the recovery support for COVID-19 to the development of climate-neutral cities, and everyone thought that it could be clearer. Again a sign of how cities and regions are moving faster towards climate change than nations.

— -
The Story Behind What’s on Our Plates — How Food Production is Harming the Planet
By: Economix Feb Ui
Tags: Food Waste, Climate Action, Environmental Issues, Environment, Climate Change

Profit over forest — a lesson from Brazil

“When a forest is lost, it is gone forever. Recovery may occur but never 100% recovery,” -Dr Michelle Kalamandeen, Amazon rainforest tropical ecologist

The consumption of red meat, milk, coffee, and sugar costs us more than the price we pay to purchase these items. Brazil learned about this the hard way. As the world’s largest commercial cattle, largest exporter of coffee, and biggest producer of soybean, along with other outstanding predicates in the food industry, Brazil experienced first hand the great impact that agriculture can have on the environment. With President Jair Bolsonaro securing the land-opening permission for farming, logging, and even mining, the rate of deforestation in the Brazilian Amazon is extremely high. According to analysis of satellite data provided by Amazon rainforest ecologist, more than 13,000sq km of the Brazilian Amazon was burned, just in the first seven months of 2020. This is more than eight times the size of London. This high rate of deforestation has strong correlation with the occurrence of forest fire since in tropical rainforest. Human activities such as agriculture and ranching constitute the direct underlying causes of fires (Butler, 2012).

Aside from the fire caused by deforestation, another major problem that countries with large agricultural industries have been going through was drought, which increases fire incidences in forests. This is directly related to the declining Northern Hemisphere aerosol production caused by global warming which tends to result in anomalous variation of sea surface temperature. The change in sea surface temperature is driving large-scale swings in precipitation over Amazon, making it more prone to wildfire. This is proven correct, looking at the large number of forest fire cases in Brazil. Back in 2019, the Amazon rainforest wildfires gained international attention and concern as the forest actually acts as the world’s largest terrestrial carbon dioxide sink. Brazil’s National Institute for Space Research (INPE) estimated that over 906 thousand hectares of forest within the Amazon biome has been lost to fires in 2019. The fuss over the Amazon forest fire may have petered out, but the reality now is even more startling. INPE reported that in the first half of 2020, deforestation was up 25%, compared to the same period last year. It is hard to imagine that the food on most of our plates is what causes this huge destruction.
How to Build an App with React + Flask
By: Ran, Reine
Tags: React, Programming, Flask, Python, Software Development

How to Build an App with React + Flask

Image from link

Note: If you’d like to read about building + deploying your React-Flask project, do check out this tutorial.

I mostly did AI related stuff back in my undergrad years but haven’t had the chance to go into web development until my final semester of school. Even though AI was really interesting, I figured that the only way I can show others what I’m doing with it is to put it on the web.

With that thought, I learned Flask and React separately and these days I wanted to figure out how to use both Flask in conjunction with React so I can create applications with better looking interfaces.

The problem is, the first few tutorials I looked at were way too complicated (like, I just wanna make an API call from React front-end to Flask back-end that’s it, do I really have to run eject, use another UI framework, etc?).

After a few tries, here’s one that (I think) is really concise (probably will only take you 10 mins to complete).

Let’s get started! ᕙ(^▿^-ᕙ)
Machine Learning in production: Keras, Flask, Docker and Heroku
By: Aissam Outchakoucht
Tags: Herokuapp, Deep Learning, Flask, Docker, Machine Learning

In this tutorial we will try to walk together through all the building blocks of a Machine/Deep Learning project in production, i.e. a model that people can actually interact with.

Broadly speaking, we’ll create a web interface in which a user could upload an image, then a bit of Deep Learning magic comes into play, and Bingo! 🎉 we get a text revealing what does that image represent.

I KNOW, it’s not rocket science, it’s just image recognition, I haven’t reinvented the wheel. In fact I’m going to be even lazier and .. guess what ! .. I will be using an already trained model 😜

Keep in mind that the idea behind this tutorial is not to teach you Deep Leaning but rather to explore the pipeline of DL in production. What really matters is when we’ll be creating an API to interact with our model, “Dockerizing” it and deploying it.

The codes used in this tutorial are available on my GitHub [here].

GO ! GO ! GO !
Creating a Flask Server to Run even on System Restart
By: Nitesh Mishra
Tags: Programming, Flask, Python

We have been in various situations where we need to keep our flask server running 24x7 on our local system or any other servers(for eg. Windows Server).

So let's now achieve our goal, for that we will be creating a system Service which can run how we want. We will be creating this Service using two things

1. Creating a .bat file

2. Creating a service using NSSM

Building a python script file

1.Copy the path of the activate.bat file for your conda environment. It is present at location ……C:\Users\acer\anaconda3\envs\env_name\Scripts\activate.bat

2. Call the app.py file of your flask app as ……

call python app.py

So your script_name.bat file looks like...

call “C:\Users\acer\anaconda3\envs\env_name\Scripts\activate.bat”

call python app.py

NOTE:

sometimes there may be a case where you can’t find the activate.bat file in the script folder of your env so in that case, you can do this…
Flask web server 與 API 實作
Tags: Flask

運用python flask架設輕便網頁伺服器, 並用 API 進行串接.

架設web server:

from flask import Flask # declare Flask object

app = Flask(__name__) # initialize Flask object

@app route(‘/’) 建立主網域下的 ’/’ 網址. 如: http://www.Lawrence.com/

def function(): # 在 app route之後定義的函數, 當該網域app被呼叫時就執行此function

return (‘Welcome to your first website!’)
How to Deploy a Flask Project to a Server?
Tags: Flask Framework, Flask, China, Flask Python Appengine, 21yunbox

Flask’s Official Website

Flask is a lightweight web framework that was developed based on: Python, WerkzeugWSGI, and Jinja2 template engines. It also has has a wealth of open source plug-ins.

21YunBox provides a very simple Flask deployment method. 21YunBox allows you to quickly deploy in a static site environment.

Register as a 21YunBox member On Gitee Fork flask example Create a cloud service on 21YunBox, and allow 21YunBox to access your code base Create with the following configuration:

If you’d like a step by step example, please refer to this example video: How to deploy the Flask project to the server?

Why Choose 21YunBox?

21YunBox is a Cloud Service platform based out of Beijing. Our services enable your team to be more effective in leveraging the growing opportunity within China by hosting your sites at blazing speeds with an operational and maintenance free solution. We offer an easy and budget friendly, end-to-end web platform deployment service for all applications from small teams to large enterprises. 21YunBox, also offer full support in obtaining your ICP license allowing you to legally host online content inside of Mainland China.

To learn about the differences between 21YunBox and these foreign (outside of China) cloud service platforms? You can refer to:
RuntimeError: No application found.
By: Na Ran
Tags: Flask, Sqlalchemy, Python

Error in Flask while creating DB.

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

This worked for me.
FLASK — endpoints
By: Ankit Nigam
Tags: Flask, Endpoints

my learning notes on FLASK endpoints.

This is just an understanding of URL endpoints and How FLASK helps in creating them.

These are just a handwritten notes from my learning but these will be give little insight to FLASK.

Just give it a try and raise in some confidence in FLASK.

We will connect soon with some real implementation for these endpoints.

Stay cool..
Python Web Flask — 實作 Flask-Migrate更新SQL資料庫
By: Sean Yeh
Tags: Flask Framework, Python Web Development, 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
Flask YouTube Audio Downloader
By: Anil Poudyal
Tags: Youtube Downloader, Download, API, Flask, Python

Make virtual environment in anaconda

conda create --name yt-downloader python conda activate yt-downloader

Installing required libraries

We will be installing flask framework for parsing and getting web requests, youtube-dl library for getting official video URL and downloading to server side and flask-cors for handling cross site origin resource error that appears when we fetch data from third party websites.

pip install flask

pip install youtube-dl

pip install flask-cors

Flask initial setup

app.py

Implementation

Now let's improve on to above code and write that actually downloads the audio

See it working

This project is hosted in https://yt.caretsys.tech/
How to download files in Flask
By: Kayathiri Mahendrakumaran
Tags: File Download, Python File Download, Download Api, Flask, File Download Flask

In this Flask tutorial, we’re going to discuss how to return files.

There are two components in this process.

HTML

We have to define an HTML href , which will call the respective Flask API for downloading the file.

<script>

var download_req_id=123;

</script> <a href="http://localhost/download"

onclick="location.href=this.href+'? download_req_id='+download_req_id;return false;">



Download

</a>

Flask

The Flask component will have a function that will return the file that has to be downloaded.
Tensorflow Serving model Creation and its deployment in FLASK then in Docker and Kubernetes.
By: Sairam Alavuru
Tags: Tfserving, Flask, Object Detection, TensorFlow

I’ll explain a way to create servable model in Tensorflow and deploy it in multiple platforms and frame works like Flask, Docker and Kubernetes
Let’s Parse the Web
By: Nil Madhab
Tags: Coding, Python, Scraping, Flask, Web Development

parse_index Method and Selectors.

As mentioned before, we have to click on a link in order to see the data after logging in. So now, how do we look for this link?

If you are on Chrome (or Chromium even) or Firefox, if you press Control-Shift-C you will see a window show up in the browser. Then click on the “Inspector” tab. Or you can directly go there by right-clicking anywhere on the page, then by selecting the “Inspect element” menu. This shows us the elements and tree of the HTML document. We can see that the link (aka the anchor or <a> tag) is inside a <p> tag. So our path is basically p > a . Interpret it as "go-to a from p ". Now we have two options. We can either use CSS Selectors or XPath. XPath is very powerful and has a lot of functionality. However, CSS Selectors can get the job done perfectly and are far more simple. So for this tutorial, we will use CSS Selectors.

To select an <a> tag inside the <p> tag, we can simply use the selector string p a . This will select all the paragraph tags anchor children (both direct and indirect). But we want direct children here. So we use p > a . To get an attribute of a selected tag in CSS Selector, we use a "pseudo-element selector" called attr() and pass the name inside the parentheses of the attribute whose value we are interested in. We use double colons to specify that we are using a "pseudo-element selector". So the selector string is, "p > a::attr(href)" and now we pass this as the first argument of the response object’s css method (which tages a CSS Selector and returns all the selected elements aka a selection ). To get the first value off of this, we use the get method of selection. There is also a method called extract for selection objects but that will return a list of all the values from all the elements of the selection, which we don’t want right now.

I hope now you can understand what was going on in line 15.
Harvard CS 50x — Week 9 (Flask). (This is a summary of week 9 from the…
By: Janine L
Tags: Computer Science, Cs50, Software Engineering, Flask, Python

(This is a summary of week 9 from the Harvard CS 50x series. Visit this page to see more from this series! )

It’s currently a Friday night in London, and I’m feeling a little exhausted. Really looking forward to the holidays now!

However, before I distract myself by dreaming too much of the upcoming holidays, I’m spending my Friday night catching up on the second last video of CS50x. This week’s focus was Flash.

Summary

Flask → A web app framework mainly used for Python

Design Pattern (Ways that humans write code)

MVC (Model, View, Controller)

Flask has certain organisational recommendations

Example of an organisational recommendation in Flask

“flask run” → starts flask app

GET → request.args

POST → request.form

Reusability of code

Layouts + use of Jinja

Froshims

Error checking

flask_mail

Sessions

Example of sessions represented by a “stamp on the hand”

Cookies

Logging in / out

JavaScript

“%” → wildcard for SQL commands

JSON(JavaScript Object Notation) → jsonify (takes a python list and returns it in a JSON format)

jQuery

AJAX

Thoughts

This week was really straightforward for me as the principals covered have already been explained to my previously during my Bootcamp course with Flatiron School. Nonetheless, it was intriguing to see everything written in Python using Flask. Can’t believe I only have 1 week of CS50x left - then I’ll be done :)!

Links to Assignments

No assignment this week.
Next time use create-flask-app
Tags: Ssk, Open Source, API, Flask, Python

something like npx create-react-app, dijango-create-project. For flask projects

Photo by Sol Mitnick on Unsplash

Hello world, Welcome back. We all love to automate small stuff that takes long time to setup. So I have automated few things and here we go.

I have created this create-flask-app project to easily get started with your Flask- API application.

what will this do

This project create a app template for getting started with api in 0 time. It comes with Docker-file to build image and setup CI/CD. It also creates virtual env, Install packages(Globally). This setup is for SQL projects (Nosql support — contribution needed). It comes with DB migration file(migrate.py) to migrate databases(flask-migrate, flask-sqlalchemy). It creates blueprints directory(traditionally known as views). It auto generate secret key for app. It auto generate requirements.txt

How to run

cd to your working folder — (the folder you want to create your app)

python(3) path-to-folder/create-flask-app

And contribution to this project is welcomed.
A not-so-quick introduction to Flask part 1: Installing Python and Flask
Tags: Programming, Web Development, Python3, Flask, Data Science

Lets install Python:

Unlike HTML, CSS, and JavaScript, We need to install python in order to functionally code with it. The python install is fairly quick and simple.

Our first step is to head to the python website at https://www.python.org

2. Select the download button at the top of the page

3. At the time of writing this post the newest python release is 3.9.0, this is what we will be using.

4. Open the Python setup .exe file

Make sure that the Add Python 3.9 to PATH box is checked before continuing with Install Now

5. Congrats! Python is now successfully installed.

Lets install Flask:

Now that we have a successful Python installation, We need to install the Flask package using the Python pip command in our Terminal.

This command will differ slightly depending on your Operating System. In this tutorial we will be using Windows, But for other readers I have you covered.

Windows Users:

Open your start menu and type cmd into your search bar.

2. Open your terminal and type the following command

pip install flask

3. Ensure Flask was installed successfully

you can do this by simply searching for the flask package in your terminal with this command

where flask

Now that we have Python and Flask successfully installed we can continue on to creating our initial flask project in Part 2.

love what I do and want to see more? leave a clap and a comment, or support my caffeine addiction directly at the link below.
ByteSize: Performant Storage with Flask + React
By: Spencer Porter
Tags: React, Programming, Python, Flask, Web Development

ByteSize: Performant Storage with Flask + React

Photo by Cobro on Unsplash

In the last tutorial we started putting together a rudimentary link preview component. Starting with the Microlink library, we were able to allow our users to enter a URL address and see an automatically generated OpenGraph preview of the link.

It’s rough though. If we are outside of the caching windows, Microlink will rescrape the entire site. While this sounds wonderful from a “freshness” point of view, it can be death for our site, with loading times approaching ~20 seconds for uncached results.

Brutal.

We have to find a way to bring down that latency to a much more acceptable range.

Sketching it out, we have a few options:

Cache the response ourselves for a longer period of time. Store the data persistently in a database

Caching ourselves could help quite a bit, as our latency would drop to ~5–10ms, but depending on the amount of users and the length of time we store it for the costs could quickly add up.

A database would be more economical for long term storage, but that brings our latency back up into the ~50–100ms range, which when you factor in component rendering that puts us back into an area we’d rather not be.

What we could do is combine the two, using the database to store all the requests, and a smaller caching window to ensure frequently accessed routes are accessed much faster.

If you just want to get the code, you can find the repo here
Flask Error: [Errno 98] Address already in use
By: Oindrila Sen
Tags: Flask Error, Flask, Python Flask, Python3

While running a Flask application initially, an error that popped up, again and again, is :[Errno 98] Address already in use

The flask error is quite clear, but the resolution was not!

When you are running FLASK and building an application, you may forget, or sometimes you could not close that application. Thus re-running your application on localhost may end up in this error.

I usually work on Jupyter Notebook on my MAC and sometimes on the python terminal. I tried to find the running session and kill those but eventually ended up killing my up-and-running Jupyter Notebook session. Well, if you have been there and done that, you will know how it feels.

What worked for me is changing the port every time I ran my application. It worked just fine!

so instead of doing this:

if __name__ == '__main__':

app.run(use_reloader=False, debug=True)

You can do this:

if __name__ == '__main__':

port = 5000 + random.randint(0, 999)

print(port)

url = "http://127.0.0.1:{0}".format(port)

print(url)

app.run(use_reloader=False, debug=True, port=port)

Ignore the print statements. I just wanted to see how it is working! Also, once you have your application in a working state, you can go back to the first one.

If you are looking for some tips to deploy your Flask application, here is an example:

Deploy Your First Machine Learning Model using Flask

Please clap once if it really helps you to fix your problem.

Thank You for Reading!
つくったもの：GitHub のアイコンっぽい画像を生成する Flask アプリ
Tags: Flask, SVG

pn11/gh-icon-generator

Generate GitHub-like icons. pip3 install -r requirements.txt Random pattern is saved as icon.svg by running the…
First Steps with Flask
By: Tobias Wissmueller
Tags: Flask Framework, Tutorial, Flask, Docker, Python

First Steps with Flask

For a project I had the need to bootstrap a small web application.

Usually I run around the Spring-Boot camp, but this time I thought I try creating a web app with Flask.

As always, that service gets deployed in a Docker container.

First, the project directory gets created.

> mkdir flask-first-steps && flask-first-steps

> mkdir app

Then we create two files.

./app/main.py

./Dockerfile

The Dockerfile has to look like:

FROM tiangolo/uwsgi-nginx-flask:python3.8

COPY ./app /app

And contents of main.py are:

from flask import Flask

app = Flask(__name__)



@app.route('/')

def hello_world():

return 'Hello, World!'



if __name__ == "__main__":

# Only for debugging while developing

app.run(host='0.0.0.0', debug=True, port=80)

Let’s build the image.

> docker build -t myflaskservice .

> docker run -d --name myflaskservice -p 8080:80 myflaskservice

Quick check to ensure its up and running curl 127.0.0.1:8080

Feel free to buy me a coffe if you liked this post.

Resources
Interpreted: Why Flask+React Should Be The Go-To Stack for New Startups
By: Spencer Porter
Tags: Programming, React, Entrepreneurship, Flask, Python

Interpreted: Why Flask+React Should Be The Go-To Stack for New Startups

Photo by Joshua Reddekopp on Unsplash

In honour of #nonuancenovember, I wanted to give my take on why you should use Flask and React for your next project. While there are an almost unlimited number of stack combinations, Flask and React provide an incredibly versatile platform to build even the most ambitious web applications.

These are my top 5 reasons why you should take the leap:

1. Easy to Learn

Python is the perfect beginners programming language. Flask is a dead simple web server. All it takes is 5 lines of code to get from a blank page to hello world.

Seriously. Five Lines.

The divide between Python and JavaScript is a very small one, and picking up React after JS only takes a few months of practice. You can get from never writing a line of code to being a proficient full-stack developer within a year, which is hard to impossible to say of other multi-language stacks.
Flask app on Google Colab with html, CSS and Javascript
By: Phan Nhan
Tags: Google, Colab, Demo, Flask, Machine Learning

Google Colab is great for Machine Learning projects. Not only that Google Colab provides us the free use of the Tesla T4 GPU, but also, it offers an integrated workspace with other Google Services. For example, one can host their data on Google Drive and load it into Google Colab for model training. Another function that not a lot of people know is that it can also help deploy a web application (for demo purpose) in the most seamless way.

When running a Flask app on local machine, we can access it through localhost. However, we cannot access the localhost on Google Colab, because it runs on a virtual machine. In this case, we have to rely on flask-ngrok, a Python library, to expose the server to a public URL.

In this article, I'll walk you through the process of running a FlaskApp (with CSS and JavaScript) on Google Colab using flask-ngrok.

0. Create a working folder in your Google Drive and start Colab Notebook.

Mount Google Colab to Drive

from google.colab import drive

drive.mount('/content/gdrive')

A window will pop up and ask for permission to your Google Drive. Allow it, copy the key, paste in the box then Enter. After that, your notebook is mounted with your Drive. You can view the folder directory on the left hand side panel.

2. Install flask-ngrok to Google Colab

!pip install flask-ngrok

3. Create a simple Flask app. You can either write this in the notebook code cell or in the Python Script within the working folder.

from flask_ngrok import run_with_ngrok

from flask import Flask, request, render_template app = Flask(__name__) @app.route("/")

def home():

return "<h1>Running Flask on Google Colab!</h1>"



app.run()

run_with_ngrok(app)

If running from Python script inside the folder, you can call:

!python <path_to_script>

to run the app.

When the cell runs, it will provide a secure URL. Traffic stats can be used to debug in case of any errors in your web app.

Click the second link to view your web app.

But wait, our app now is very simple. What if I want to decorate it using CSS and JavaScript? Where should I put it?

4. First, I'll git clone my template and static folder into the working folder on Drive.

%cd <your working folder>

!git clone <your git>

5. Define paths to templates (html) and static (CSS and JavaScript):

TEMPLATE = '/content/gdrive/MyDrive/flask_on_colab/templates' STATIC = '/content/gdrive/My Drive/flask_on_colab/static'

6. Link the template and static folders into the Flask app:

app = Flask(__name__,

template_folder=TEMPLATE,

static_folder=STATIC) @app.route("/")

def home():

return "<h1>Running Flask on Google Colab!</h1>"



app.run()

run_with_ngrok(app)

Now your web frontend looks a lot better. This method is simple and offer you a quick way to demonstrate your project with your peers. It also utilizes the capacity of Google Drive to handle data, free yourself from unnecessary environment bugs and allows you to make quick change on modeling and training before moving on into production.
ByteSize: Setting up with Flask + React Boilerplate
By: Spencer Porter
Tags: React, Programming, Python, Flask, Web Development

ByteSize: Setting up with Flask + React Boilerplate

Photo by Mirko Blicke on Unsplash

I use Flask and React. A lot.

As I reference setting up an application with them for most of my tutorials, I figured it would be worthwhile to put together a quick instructional for how to get up and running instead of repeating it each time (DRY and all that).

Getting started with React when you’re using Flask can seem a little daunting at first. Between two different package mangers (pip and npm), some customization needed for properly project layout, and a lack of consistent guides, it rarely seems all that straightforward.

I personally use Webpack for my projects, as I find that you don’t have to make as many changes as you do with create-react-app to get setup. If you were interested in learning how to set up with CRA though, Miguel Grinberg has a great tutorial here.

If you were just looking for the code, you can find the repo here
Flask in Google Colab
By: Rahul Gothwal
Tags: Google Colab, Ngrok, Web Development, Flask, Python

To get things working, just head over to Goggle Colab

and create a new notebook and name it whatever you like.

now just connect your runtime and use this commands in the cell

!pip install flask-ngrok

this will download and install ngrok on colab virtual instance and will make your Flak apps running on localhost available over the internet via the excellent ngrok tool.

Cool, now we are ready to test our app.

the only extra line of code you need to add to your app is

from flask_ngrok import run_with_ngrok run_with_ngrok(app)

and this will make a public IP available until your colab is running.
ByteSize: Infinite Scroll with Flask and React Pt.2
By: Spencer Porter
Tags: React, Programming, Web Development, Flask, Python

The Code

We’ll start off by the components we’ll be using at the top of our Infinite Scroll component file (in app\static\src\InfiniteScroll.jsx)

Next we’ll create the GridList and GridListTile components in the returned portion of the InfiniteScroll function.

Feel free to play around with the cellHeight and cols (columns) attributes for your own projects, the cell height obviously adjusting the height and width of the image, and columns adjusting how many images are displayed per row.

The cols and rows arguments in GridListTile allow you to set the height and width of our images as increments of the cellHeight from the GridList component. This let’s you make certain images take up more space than others, giving a nice aesthetic.

I used the Modulo (%) operator in a ternary statement to make it that images will have the width of three slots on the tenth photo, and two slots on every twentieth.

We will also need to include the styling for these elements above as well.

The gridList class can be adjusted based on how wide you want the overall grid to be.

With that finished our feed currently looks like this:

While this is great, the coloring of the images can be a little conflicting and overwhelming, lacking a bit of coherence. We can change this by adding some grayscale to desaturate the colouring of the images and bringing it to a similar level. We can then make a CSS hover selector that removes the grayscale when a user navigates over a picture.

We can make these adjustments using the image class we already defined in our image tag using the makeStyles object.
JWT authentication with AWS Cognito and Google
By: Jegnesh Gehlot
Tags: Aws Cognito, Flask, Python3, Jwt Token

This article will cover the essentials of accessing authenticated endpoints/URL with JWT that uses AWS Cognito & Google as an IdP.

The web application is written in python using flask framework.

The first step will be the configuration of AWS Cognito user pools & Google. The tutorial below from Amazon AWS details the steps to configure AWS Cognito user pools and Google.

AWS Cognito Workflow

AWS Cognito Workflow (Source: Amazon)

Web App Workflow

Step 1: Client will be presented with the Google sign in page.

Step 2: Once authenticated the user will be redirected to authenticated URL/endpoint

Environment Variable Definitions

Note: Cognito url (ref. as <myurl> in the table above) can be found under: AWS Cognito > User Pools > [MyPool] > Domain name > Amazon Cognito Domain

Code walk-through

Entry point:

The following code composes an URL with a state variable (mitigating cross-site request forgery) and re-direct the request.

2. Configuring callback URL:

Under the callback function, we first check the state variable value to make sure it matches with the one that was passed with the initial request. After that, we extract the code that is part of the URL as a query parameter. We then use the code to get an access token. On successful retrieval of the access token, we will save it as a cookie and redirect the request to our authorized endpoint i.e. user homepage.

3. JWT and Authentication:

The jwt_required decorator is used to confirm the validity of the stored token. In the function definition below we have added some steps to verify the KID and token signature. AWS Cognito generates two RSA keys and uses one of them to sign the token. Therefore, we first extract the KID and signature from the current header and try to match with public keys downloaded from AWS. Once verified, we return the key in PEM format.

4. Test

One important note. If you receive ‘algorithm not supported’ error while accessing an authorized endpoint that means you do not have cryptography package installed that provide basic RS256 algorithm functionality.

The complete code is available on GitHub. Any constructive feedback is welcome.
Beralih ke FastAPI sebagai Pengganti Flask untuk Produksi Model Machine Learning
By: Fahmi Salman
Tags: Asynchronous, Machine Learning, Flask, Hacker, Production

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
flask網頁建設主題二
By: Steven Wang
Tags: Flask

followers關係表

follower_id /followed_id結構

1 followed 2 and 3

3 followed 2

2 follower 1 and 3

3 follower 1

user.id 與 follower.id 會找出1關注了誰

user.id 與 followed.id會找出2被誰關注

建立followers table

models.py

followers = db.Table('followers',

db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),

db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))

)

followers table 是一張描述關係的表

因為table數據是描述關係不用class定義

欄位本身採用ForeignKey外鍵（必須是已經存在id的資料)

class User

多對多的關係

followed = db.relationship(

'User', secondary=followers,

primaryjoin=(followers.c.follower_id == id),

secondaryjoin=(followers.c.followed_id == id),

backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')

primaryjoin=(followers.c.follower_id == id) /找出followed

secondaryjoin=(followers.c.followed_id == id) /找出follower

backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')

/ 可以直接對follower followed操作

因為更動了models.py 新增了關係的連接表followers

python manager.py db migrate -m “add followers”

python manager.py db upgrade

進入python shell測試

from twittor import db, create_app

from twittor.models import User

app = create_app()

app.app_context().push()

User.query.all()

User.query.count() ‘計算個數

u1=User.query.get(1)

u3=User.query.get(3)

u1.followed ‘u1.followed是一個list可以透過迴圈看其中的內容如下

<sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x1067b2b38>

for u in u1.followed:

… print(u)

…(尚無資料)

follow 實作

u1.followed.append(u3)

db.session.commit()

for u in u1.followed:

… print(u)

id=3, username=test1, email=test1@test1.com,password, password_hashpbkdf2:sha256:150000$KT55a5ra$5f09f637f20f1a7577a01cde374ec8a7c8a7a95e5aaa0b385c9b6084951f2414 (u1.followed有資料)

unfollow 實作

u1.followed.remove(u3)

db.session.commit()

for u in u1.followed:

… print(u)

…(無資料)

查詢

u1.followed.all() 有一個跟隨 ‘followed

u4.followed.all() 有一個跟隨

u3.followers.all() 有兩個粉絲 ‘followers

能夠這樣的followed/followers查詢因為下面models/def User的設定

def is_following(self, user)傳入一個用戶判斷是否已經followed過了

templates/user.html

自己對自己不用顯示

自己對他人需要判斷是不是is_following

>>user 被查看的用戶

>>current_user當前登入的用戶

修改__init__.py，使得profile能接受requesu的POST

app.add_url_rule('/<username>', 'profile', user, methods=['GET', 'POST'])

user.html判斷用戶點擊what按鈕

賦予按鈕name

{% if user != current_user %}

{% if current_user.is_following(user) %}

<input type="submit" name="request_button" value="Unfollow">

{% else %}

<input type="submit" name="request_button" value="Follow">

{% endif %}

router.py/def user

print(request.form.to_dict)能顯示出後台收到的資料

就可以透過request.form[‘request_button’]返回的值做判斷

if request.method == 'POST':

if request.form['request_button'] == 'Follow':

print('click Follow')

else:

print('click unfollow')

models.py/class user

def follow

def unfollow

route.py/def user

followers/followed計數器

user.followers.count()/user.followed.count()
How to create a flask application from scratch
Tags: Flask, Tutorial, Python, Web Development

How to create a flask application from scratch ZaiCodes ·Nov 20, 2020

In this blog I am going take you through a basic tutorial on how to create your first flask app from scratch.

Prerequisites

PIP (Python Package Manager): https://pip.pypa.io/en/stable/

Step 1

Install virtual enviorments, virtual enviorments allow you to isolate libaries and scripts that are installed for individual projects.

pip3 install virtualenv

*use this command in your terminal

Step 2

Create and activate your virtual enviorment

MacOS:

python3 -m venv env

source env/bin/activate

Windows:

py -m venv env

./env/Scripts/activate

use this command in your terminal

Step 3

Install Flask using pip, flask is a lightweight python web framework that we will be using for this web application

pip3 install flask

use this command in your terminal

Step 4

Create a ‘flaskapp.py’ file and define a url endpoint

Step 5

Then set the flask app variable and run your flask app, ensure you use the ‘cd’ command to make sure you are in the directory where you have saved the flaskapp file before running these commands.

MacOS:

export FLASK_APP=flaskapp

flask run

Windows

env:FLASK_APP = “flask app”

flask run

Step 5

Follow url given to view your flask app in the browser

Well Done, you know have a basic flask application running, have fun coding !!
Image encryption and decryption web application using Flask
By: Vinayak Sharma
Tags: Encryption, Decryption, Hackathons, Flask, Python

A few months back I made a flask app during a hackathon. The web app helps in easy encryption and decryption of an image. It is based on the XOR operation. Upon encryption, the user is given back an encrypted image along with a key. Later on, the user can upload the encrypted image back to the web app along with the key, and in return, the user is given back a decrypted image only if the key entered is correct. The link to my deployed website for this project image security

The Tech stack used for making this app is Flask + Jinja framework. The sole function of this web app is image encryption and decryption.

The reason for choosing flask is because it is relatively easy to fetch or provide images in Flask. The other reason for using Flask is python (easy operations).

Kindly refer to this documentation if you want to set up a flask project.
AWS Multi-Tier Architecture
By: Boddeda Avinash
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 that 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.
Plotly Dash or React.js + Plotly.js? A side by side comparison
By: Antoine Hue
Tags: React, Plotly, Dataviz, Flask, Machine Learning

Plotly Dash or React.js + Plotly.js? A side by side comparison

Dash value proposal is to hide the complexity of writing a React Web App while presenting some data in a dashboard. Let’s do a side by side comparison with a machine learning use case Antoine Hue Nov 17, 2020·8 min read

We have seen in “Which library should I use for my Python dashboard?” that creating a data visualization in a Web dashboard is quickly getting complex and requires a framework that is doing more than stitching some plots. Plotly Dash is one such framework and is very reachable to most data scientists as the application is pure Python code.

Dash and React.js leading you to the top. Photo by Stéphane Fellay on Unsplash

At the same time, Dash is generating a Web application built on React.js, a leading Javascript framework for Web applications. Sooner or later you will feel limited by Dash. Either by the constraints or the principles of Dash, or by the lack of control on the generated app, or by the integration of the dashboard with a larger application. For example, your application may require authentication of the user, it may fetch some client data and eventually lead to the Dashboard.

What if I want to switch from Dash to a classical React.js application after my prototyping phase? Is this costly?

What if I want to skip completely the Dash phase and directly create a React.js app? Is the learning curve too steep?

In the following is shown what it means to write a Dash application and the React.js alternative, based on a use case that fits with Dash: upon user selection, the inference is performed on an Audio file using the YAMNet classifier. The inference is returning the scores as well as the waveform, these series are plotted on the dashboard.

Dashboard showing audio waveform and inference scores © the author

The code of the article is available in a Github repository tonio73/dash-to-react. This is a tutorial, more than a template to start your development. That’s why the steps to reproduce this code are explained here below.

Both versions of the dashboard are based on Plotly for the plots, Bootstrap 4 for the HTML and CSS design. The two are available as plugins to Dash and as Node.js packages for React.js.
Svelte +FastAPI ‘hello world’
By: Phil Harper
Tags: Fastapi, Svelte, JavaScript, Flask, Python

Here’s a very quick (and probably bad) guide on how to integrate FastAPI with a Svelete front end. Ideally you’d entirely separate the two, with Svelte served independently of Fast API, but if you’re like me and you want a less than perfect but easier to manage solution, maybe this is it.

I wanted to use Svelte as the front end to either Flask, or Fast API. I tried a few ways to do it and found a setup that serves Svelte using FastAPI (actually starlette’s) StaticFiles in html mode.

Setup a very basic Hello World with Fast API — return a random number which we’ll later display in Svelte. I called mine `main.py`

from fastapi import FastAPI

from fastapi.staticfiles import StaticFiles

from starlette.responses import RedirectResponse

import random app = FastAPI() @app.get("/rand")

async def rand():

return random.randint(0, 100)

2) Create a folder inside your FastAPI project for Svelte, I called mine ‘front’. Then git clone the svelte template into that folder. When you’re done, you’ll need to call `npm install` inside your svelte app directory, you can then check it works with `npm run dev`. Here’s the directory tree:

3) In main.py we’re going to statically serve the `front` and ‘front/build’ directories, then redirect all root requests to that new static `front` endpoint. In main.py, add the following:

from fastapi import FastAPI

from fastapi.staticfiles import StaticFiles

from starlette.responses import RedirectResponse

import random app = FastAPI() app.mount("/front", StaticFiles(directory="front/public", html=True), name="front")

app.mount("/build", StaticFiles(directory="front/public/build"), name="build") @app.get("/rand")

async def hello():

return random.randint(0, 100) @app.get('/')

async def front():

return RedirectResponse(url='front')

4) Lets add a function to our Svelte app which calls the /rand endpoint we made and gets a random number from our FastAPI and displays it.

<script> let rand = -1; function getRand() { fetch("../rand") .then(d => d.text()) .then(d => (rand = d)); } </script> <main> <h1>Hello {rand}!</h1> <button on:click={getRand}>Get a random number</button> </main>

5) You need to build you Svelte app on each change — as its being served via FastAPI. Type ` npm run build inside front directory.

6) Check out your app — it should work

There are certainly better ways of doing this — in Flask it’s easier to setup using serve from directory. This was inspired by a post here
How to upload multiple images with Flask ?
Tags: Flask Framework, Multiple Images, Nelsonher019, Flask, Nelsonher

In this example we will learn how to upload multiple images using Flask in a very simple way

1) Creation of virtual environment

In this case I decided to use virtualenv but you can use pipenv if you like.

virtualenv venv

source ./venv/bin/activate

2) Installation of dependencies

pip install Flask

3 ) Flask server creation

from flask import Flask app = Flask(__name__) if __name__ == "__main__":

app.run(debug=True)

4) Endpoint upload multiple images

from flask import Flask, request

from werkzeug.utils import secure_filename

import os app = Flask(__name__) @app.route('/upload/', methods=["POST"])

def upload_image():

if request.method == 'POST':

files = request.files.getlist("files")

for file in files:

filename = secure_filename(file.filename)

try:

working_directory = os.getcwd()

file.save(working_directory + "/files/" + filename)

except FileNotFoundError :

return 'Error, folder does not exist'

return "Success" if __name__ == "__main__":

app.run(debug=True)

5) Frontend with JavaScript