#FlaskApp
Explore tagged Tumblr posts
asadmukhtarr · 3 days ago
Text
Setting Up Flask
0 notes
skillgain-academy · 2 years ago
Text
How to Organize Your Flask Apps Using Blueprints
Flask is a simple, easy-to-use micro web framework for Python that can help you build scalable and secure web applications.
There are occasions when programmers will place all of their logic in a single file named app.py. Many tutorials can be found online that use the same format. But for a big app, it's not a good approach.
You are obviously going against the Single Duty Principle by doing this, which states that each component of your application should only be handling one responsibility.
If you've used Django, your project may have been broken up into many modules. Additionally, you may organise your Flask applications using Blueprints, a Python module-like built-in idea.
How a Flask Application Appearance?
Your project structure will like this if you construct a simple application using the Flask documentation:
/myapp 
└── app.py
Isn't the folder wonderfully organised? The only thing you have is an app.py file that contains all of the application functionality.
Let's look at the app.py file:
from flask import Flask
app = Flask(__name__)
# Some Models Here
# Routes related to Products Page
# Routes related to Admin Page
if __name__ == '__main__':
    app.run(host=’0.0.0.0’,port=5000,debug=True)
When you imagine that you have created a large-scale programme, doesn't that look messy? You have scattered your models and different routes throughout the same file.
How Do Blueprints Address the Issue?
Flask Blueprints now come into play in this scenario. By grouping the logic into subdirectories, blueprints aid in the structure of your application. Additionally, you can put the logic and static files  all in the same subdirectory.
Consequently, your similar application will now look like this because to Blueprints:
/blueprint-tutorial
├── /myapp_with_blueprints
│   ├── __init__.py
│   ├── /admin
│   │   └── routes.py
│   ├── /products
│   │   └── routes.py          
├── app.py
You can see that your concerns are well separated at this point. The logic for admin is located in the admin folder, the logic for products is located in the products folder, and so on.
Use of Blueprints
Now that you understand what problems Blueprints solves, let's see how we can use Blueprints in our applications.
Defining a Blueprint
In the admin/routes.py file, let's define our very first blueprint for the admin functionality:
from flask import Blueprint
# Defining a blueprint
admin = Blueprint(
    'admin', __name__,
    template_folder='templates',
    static_folder='static'
)
You can import Blueprint from the Flask library because it is a built-in Flask concept. The first parameter when creating an object of the Blueprint class is the name you wish to give your Blueprint. Internal routing will later use this name, as we'll see below.
The second option is the Blueprint package's name, which is often __name__. This aids in locating the blueprint's root path.
Optional keyword arguments are supplied as the third and fourth parameters. You declare that you'll use blueprint-specific templates and static files by defining the template folder and static folder options.
How to Create Blueprint Routes
You may now use the blueprint you developed for the admin-related functionality when establishing routes for the admins.
from flask import Blueprint
# Defining a blueprint
admin = Blueprint(
    'admin', __name__,
)
@admin.route('/admin')   # Focus here
def admin_home():
    return "Hello Admin!"
Concentrate on the line where the route is specified in the given snippet. We have used @admin bp.route('...') rather than the typical @app.route('...'). This is how a route is connected to a certain blueprint.
Ways for Registering Your Blueprints
You currently have a route registered to a blueprint. But will your app be aware of this blueprint automatically?
So let's get going. We will construct a Flask app and register our blueprints there in the __init__.py file:
from flask import Flask
app = Flask(__name__)
from .admin.routes import admin
# Registering blueprints
app.register_blueprint(admin)
Using the register_blueprint() method and the blueprint's name, we register the blueprint. For even more customisation, you can also supply the procedure other parameters. One of these is url prefix, which you could need.
app.register_blueprint(admin, url_prefix='/admin')
Similar to that, if you have other blueprints, you can register them.
1 note · View note
learnstowin · 2 years ago
Link
0 notes
for-the-user · 8 years ago
Text
docker compose... so i only need to type one command
So I guess this is the entire purpose for the existence of docker compose? So here's how to do exactly the same thing as in my last post
Let's assume the docker daemon is already installed.
Install docker-compose.
$ curl -L https://github.com/docker/compose/releases/download/1.15.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose $ sudo chmod +x /usr/local/bin/docker-compose $ docker-compose --version docker-compose version 1.15.0, build e12f3b9 $ docker-compose version docker-compose version 1.15.0, build e12f3b9 docker-py version: 2.4.2 CPython version: 2.7.13 OpenSSL version: OpenSSL 1.0.1t 3 May 2016
Put a docker-compose.yml into your working directory:
$ tree . ├── Vagrantfile ├── app │   ├── Dockerfile │   ├── index.py │   └── pewpew.wsgi ├── db │   └── Dockerfile ├── docker-compose.yml └── rp ├── Dockerfile └── site.conf version: '2' services: reverseproxy: build: /srv/rp ports: - "80:80" links: - flaskapp:flaskapp depends_on: - flaskapp flaskapp: build: /srv/app ports: - "5000:5000" links: - mongodb:mongodb depends_on: - mongodb mongodb: build: /srv/db ports: - "27017:27017"
Build those images & run those containers
$ docker-compose up -d . . . Creating mongodb ... Creating mongodb ... done Creating flaskapp ... Creating flaskapp ... done Creating reverseproxy ... Creating reverseproxy ... done
Check what's going on
$ docker-compose ps Name Command State Ports ----------------------------------------------------------------------------------- flaskapp gunicorn -k eventlet -b 0. ... Up 0.0.0.0:5000->5000/tcp mongodb docker-entrypoint.sh mongod Up 0.0.0.0:27017->27017/tcp reverseproxy nginx -g daemon off; Up 443/tcp, 0.0.0.0:80->80/tcp
Send a request to the reverse proxy
$ curl http://127.0.0.1 Pew Pew! {u'storageEngines': [u'devnull', u'ephemeralForTest', u'mmapv1', u'wiredTiger'], u'maxBsonObjectSize': 16777216, u'ok': 1.0, u'bits': 64, u'modules': [], u'openssl': {u'compiled': u'OpenSSL 1.0.1t 3 May 2016', u'running': u'OpenSSL 1.0.1t 3 May 2016'}, u'javascriptEngine': u'mozjs', u'version': u'3.4.6', u'gitVersion': u'c55eb86ef46ee7aede3b1e2a5d184a7df4bfb5b5', u'versionArray': [3, 4, 6, 0], u'debug': False, u'buildEnvironment': {u'cxxflags': u'-Woverloaded-virtual -Wno-maybe-uninitialized -std=c++11', u'cc': u'/opt/mongodbtoolchain/v2/bin/gcc: gcc (GCC) 5.4.0', u'linkflags': u'-pthread -Wl,-z,now -rdynamic -Wl,--fatal-warnings -fstack-protector-strong -fuse-ld=gold -Wl,--build-id -Wl,-z,noexecstack -Wl,--warn-execstack -Wl,-z,relro', u'distarch': u'x86_64', u'cxx': u'/opt/mongodbtoolchain/v2/bin/g++: g++ (GCC) 5.4.0', u'ccflags': u'-fno-omit-frame-pointer -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -O2 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wno-missing-braces -fstack-protector-strong -fno-builtin-memcmp', u'target_arch': u'x86_64', u'distmod': u'debian81', u'target_os': u'linux'}, u'sysInfo': u'deprecated', u'allocator': u'tcmalloc'} [u'admin', u'local']
What do the containers look like now?
$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 774ad38c93d7 srv_reverseproxy "nginx -g 'daemon ..." 3 minutes ago Up 3 minutes 0.0.0.0:80->80/tcp, 443/tcp reverseproxy 1094581a5a17 srv_flaskapp "gunicorn -k event..." 3 minutes ago Up 3 minutes 0.0.0.0:5000->5000/tcp flaskapp 0f4c7f0d7175 srv_mongodb "docker-entrypoint..." 3 minutes ago Up 3 minutes 0.0.0.0:27017->27017/tcp mongodb $ docker-compose ps Name Command State Ports ----------------------------------------------------------------------------------- flaskapp gunicorn -k eventlet -b 0. ... Up 0.0.0.0:5000->5000/tcp mongodb docker-entrypoint.sh mongod Up 0.0.0.0:27017->27017/tcp reverseproxy nginx -g daemon off; Up 443/tcp, 0.0.0.0:80->80/tcp
And the images?
$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE srv_reverseproxy latest 9283f67c41fb 3 minutes ago 107MB srv_flaskapp latest e3b9a8003c5d 3 minutes ago 683MB srv_mongodb latest 397be1d78005 4 minutes ago 359MB nginx latest b8efb18f159b 13 days ago 107MB mongo latest 6833171fe0ad 13 days ago 359MB python 2.7 fa8e55b2235d 2 weeks ago 673MB $ docker-compose images Container Repository Tag Image Id Size ---------------------------------------------------------------- flaskapp srv_flaskapp latest e3b9a8003c5d 651 MB mongodb srv_mongodb latest 397be1d78005 342 MB reverseproxy srv_reverseproxy latest 9283f67c41fb 102 MB
Now previously... say you want to change something in one of the containers, you'd have to like, docker stop.. docker rm.. docker rmi.. docker build.. docker run.. blah blah blah.
Say I've changed the app output from Pew Pew! to Peow Peow Lazor Beams!!
With docker-compose:
$ docker-compose build flaskapp . . Removing intermediate container 05f624a8c37b Successfully built 0e44b2dee5fa Successfully tagged srv_flaskapp:latest $ docker-compose up --no-deps -d flaskapp Recreating flaskapp ... Recreating flaskapp ... done $ docker-compose ps Name Command State Ports ----------------------------------------------------------------------------------- flaskapp gunicorn -k eventlet -b 0. ... Up 0.0.0.0:5000->5000/tcp mongodb docker-entrypoint.sh mongod Up 0.0.0.0:27017->27017/tcp reverseproxy nginx -g daemon off; Up 443/tcp, 0.0.0.0:80->80/tcp $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2b4e890d5dcf srv_flaskapp "gunicorn -k event..." 3 minutes ago Up 3 minutes 0.0.0.0:5000->5000/tcp flaskapp 774ad38c93d7 srv_reverseproxy "nginx -g 'daemon ..." 2 hours ago Up About an hour 0.0.0.0:80->80/tcp, 443/tcp reverseproxy 0f4c7f0d7175 srv_mongodb "docker-entrypoint..." 2 hours ago Up About an hour 0.0.0.0:27017->27017/tcp mongodb
And the changes?
$ curl http://127.0.0.1 Peow Peow Lazor Beams!! {u'storageEngines': [u'devnull', u'ephemeralForTest', u'mmapv1', u'wiredTiger'], u'maxBsonObjectSize': 16777216, u'ok': 1.0, u'bits': 64, u'modules': [], u'openssl': {u'compiled': u'OpenSSL 1.0.1t 3 May 2016', u'running': u'OpenSSL 1.0.1t 3 May 2016'}, u'javascriptEngine': u'mozjs', u'version': u'3.4.6', u'gitVersion': u'c55eb86ef46ee7aede3b1e2a5d184a7df4bfb5b5', u'versionArray': [3, 4, 6, 0], u'debug': False, u'buildEnvironment': {u'cxxflags': u'-Woverloaded-virtual -Wno-maybe-uninitialized -std=c++11', u'cc': u'/opt/mongodbtoolchain/v2/bin/gcc: gcc (GCC) 5.4.0', u'linkflags': u'-pthread -Wl,-z,now -rdynamic -Wl,--fatal-warnings -fstack-protector-strong -fuse-ld=gold -Wl,--build-id -Wl,-z,noexecstack -Wl,--warn-execstack -Wl,-z,relro', u'distarch': u'x86_64', u'cxx': u'/opt/mongodbtoolchain/v2/bin/g++: g++ (GCC) 5.4.0', u'ccflags': u'-fno-omit-frame-pointer -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -O2 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wno-missing-braces -fstack-protector-strong -fno-builtin-memcmp', u'target_arch': u'x86_64', u'distmod': u'debian81', u'target_os': u'linux'}, u'sysInfo': u'deprecated', u'allocator': u'tcmalloc'} [u'admin', u'local']
Noice.
0 notes
for-the-user · 8 years ago
Text
flask docker vagrant mac inceptions
First, some vagrant preparation stuff, cos I docker doesn't play well on mac.
$ vagrant up $ vagrant plugin install vagrant-vbguest $ vagrant ssh $ sudo apt-get install -y virtualbox-guest-dkms virtualbox-guest-utils virtualbox-guest-x11 $ sudo apt-get install linux-image-extra-$(uname -r) linux-image-extra-virtual
The Vagrantfile I used looks like this.
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.provider :virtualbox do |provider| provider.check_guest_additions = false provider.functional_vboxsf = false provider.memory = 1024 provider.cpus = 1 end config.vm.define "pewpew" do |pewpew| pewpew.vm.box = "ubuntu/trusty64" pewpew.vm.box_check_update = false pewpew.vm.box_download_insecure = true pewpew.vm.network "private_network", ip: "192.168.50.14", netmask: "255.255.255.0" pewpew.vm.hostname = "pewpew.mydomain.com" pewpew.vm.network "forwarded_port", guest: 80, host: 8080, auto_correct: true# > /etc/fstab" pewpew.vm.provision :shell, inline: "echo vm.swappiness = 10 >> /etc/sysctl.conf && echo vm.vfs_cache_pressure = 50 >> /etc/sysctl.conf && sysctl -p" end config.ssh.username = "vagrant" config.ssh.pty = true config.vm.provision "shell" do |shell| shell.privileged = true shell.inline = "sudo sed -i '/tty/!s/mesg n/tty -s \\&\\& mesg n/' /root/.profile" end end
My /etc/hosts file contains this line:
192.168.50.14 pewpew.mydomain.com
My working directory on my mac looks like this:
$ tree . ├── Vagrantfile ├── app │   ├── Dockerfile │   ├── index.py │   └── pewpew.wsgi ├── db │   └── Dockerfile └── rp ├── Dockerfile └── site.conf
This directory is mounted into the Vagrant vm at /srv.
Let's go through each file:
--- /srv/app/Dockerfile --- FROM python:2.7 RUN pip install --no-cache-dir Flask==0.10.1 RUN pip install --no-cache-dir gunicorn==19.3.0 RUN pip install --no-cache-dir eventlet==0.17.4 RUN pip install --no-cache-dir pymongo==3.4.0 COPY index.py /app/ COPY pewpew.wsgi /app/ EXPOSE 5000 WORKDIR /app CMD ["gunicorn", "-k", "eventlet", "-b", "0.0.0.0:5000", "-w", "1", "index:app"] --- /srv/app/index.py --- import os from flask import Flask from pymongo import MongoClient app = Flask(__name__) db = "mongodb" client = MongoClient(db, 27017) @app.route("/") def hello(): try: server_info = client.server_info() db_names = client.database_names() client.close() return "Pew Pew!\n%s\n%s\n" % (server_info, db_names) except: return "Pew Pew! DB failing...\n" if __name__ == '__main__': app.run() --- /srv/app/pewpew.wsgi --- import sys PROJECT_DIR = '/app/' sys.path.append(PROJECT_DIR) from pewpew import app as application --- /srv/db/Dockerfile --- FROM mongo EXPOSE 27017 --- /srv/rp/Dockerfile --- FROM nginx COPY site.conf /etc/nginx/conf.d/site.conf EXPOSE 80 443 --- /srv/rp/Dockerfile --- server { listen 80; server_name pewpew.mydomain.com; access_log /var/log/nginx/nginx_access_myapp.log; error_log /var/log/nginx/nginx_error_myapp.log; location / { proxy_pass http://flaskapp:5000/; } }
Ok let's start. ssh into the vagrant box and check the kernel. To use docker you need 3.10+ or sum chit...
$ vagrant ssh $ uname -r 3.13.0-98-generic
Ok cool, install the docker daemon.
$ sudo curl -sSL https://get.docker.com/ | sh
Now let's build these images from the three Dockerfiles we have.
$ sudo docker build -t reverseproxy /srv/rp/ $ sudo docker build -t flaskapp /srv/app/ $ sudo docker build -t mongodb /srv/db/ $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE reverseproxy latest fa2ead9fdb67 11 minutes ago 107MB flaskapp latest 48ce64a24bea About an hour ago 681MB nginx latest b8efb18f159b 12 days ago 107MB python 2.7 fa8e55b2235d 13 days ago 673MB mongo latest b39de1d79a53 13 days ago 359MB
Start the database container first.
$ docker run -d -e DB_PORT_27017_TCP_ADDR='0.0.0.0' -v /srv/db:/data -p 27017:27017 --name mongodb mongo $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c610b1a11752 mongo "docker-entrypoint..." 3 seconds ago Up 1 second 0.0.0.0:27017->27017/tcp mongodb
Then start the flask application container.
$ docker run -d -p 5000:5000 --name flaskapp --link mongodb:mongodb flaskapp $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ebf6ba70b2f8 flaskapp "gunicorn -k event..." 2 seconds ago Up 1 second 0.0.0.0:5000->5000/tcp flaskapp c610b1a11752 mongo "docker-entrypoint..." 24 seconds ago Up 23 seconds 0.0.0.0:27017->27017/tcp mongodb
Send a request to the app
$ curl http://127.0.0.1:5000 Pew Pew! {u'storageEngines': [u'devnull', u'ephemeralForTest', u'mmapv1', u'wiredTiger'], u'maxBsonObjectSize': 16777216, u'ok': 1.0, u'bits': 64, u'modules': [], u'openssl': {u'compiled': u'OpenSSL 1.0.1t 3 May 2016', u'running': u'OpenSSL 1.0.1t 3 May 2016'}, u'javascriptEngine': u'mozjs', u'version': u'3.4.6', u'gitVersion': u'c55eb86ef46ee7aede3b1e2a5d184a7df4bfb5b5', u'versionArray': [3, 4, 6, 0], u'debug': False, u'buildEnvironment': {u'cxxflags': u'-Woverloaded-virtual -Wno-maybe-uninitialized -std=c++11', u'cc': u'/opt/mongodbtoolchain/v2/bin/gcc: gcc (GCC) 5.4.0', u'linkflags': u'-pthread -Wl,-z,now -rdynamic -Wl,--fatal-warnings -fstack-protector-strong -fuse-ld=gold -Wl,--build-id -Wl,-z,noexecstack -Wl,--warn-execstack -Wl,-z,relro', u'distarch': u'x86_64', u'cxx': u'/opt/mongodbtoolchain/v2/bin/g++: g++ (GCC) 5.4.0', u'ccflags': u'-fno-omit-frame-pointer -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -O2 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wno-missing-braces -fstack-protector-strong -fno-builtin-memcmp', u'target_arch': u'x86_64', u'distmod': u'debian81', u'target_os': u'linux'}, u'sysInfo': u'deprecated', u'allocator': u'tcmalloc'} [u'admin', u'local']
Nice! Now let's try with the nginx container.
$ docker run -d -p 80:80 --name reverseproxy --link flaskapp:flaskapp reverseproxy $ sudo docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 716f3c7c321c reverseproxy "nginx -g 'daemon ..." 1 second ago Up Less than a second 0.0.0.0:80->80/tcp, 443/tcp reverseproxy ebf6ba70b2f8 flaskapp "gunicorn -k event..." 19 seconds ago Up 18 seconds 0.0.0.0:5000->5000/tcp flaskapp c610b1a11752 mongo "docker-entrypoint..." 41 seconds ago Up 39 seconds 0.0.0.0:27017->27017/tcp mongodb
Send a request to the nginx vhost.
$ curl http://127.0.0.1/ Pew Pew! {u'storageEngines': [u'devnull', u'ephemeralForTest', u'mmapv1', u'wiredTiger'], u'maxBsonObjectSize': 16777216, u'ok': 1.0, u'bits': 64, u'modules': [], u'openssl': {u'compiled': u'OpenSSL 1.0.1t 3 May 2016', u'running': u'OpenSSL 1.0.1t 3 May 2016'}, u'javascriptEngine': u'mozjs', u'version': u'3.4.6', u'gitVersion': u'c55eb86ef46ee7aede3b1e2a5d184a7df4bfb5b5', u'versionArray': [3, 4, 6, 0], u'debug': False, u'buildEnvironment': {u'cxxflags': u'-Woverloaded-virtual -Wno-maybe-uninitialized -std=c++11', u'cc': u'/opt/mongodbtoolchain/v2/bin/gcc: gcc (GCC) 5.4.0', u'linkflags': u'-pthread -Wl,-z,now -rdynamic -Wl,--fatal-warnings -fstack-protector-strong -fuse-ld=gold -Wl,--build-id -Wl,-z,noexecstack -Wl,--warn-execstack -Wl,-z,relro', u'distarch': u'x86_64', u'cxx': u'/opt/mongodbtoolchain/v2/bin/g++: g++ (GCC) 5.4.0', u'ccflags': u'-fno-omit-frame-pointer -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -O2 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wno-missing-braces -fstack-protector-strong -fno-builtin-memcmp', u'target_arch': u'x86_64', u'distmod': u'debian81', u'target_os': u'linux'}, u'sysInfo': u'deprecated', u'allocator': u'tcmalloc'} [u'admin', u'local']
Awesome, we can also go to our http://pewpew.mydomain.com URL in a browser on our mac, as we have forwarded the port on our Vagrant box and added a local DNS entry in /etc/hosts remember?
0 notes