Categories
Flask

Python Web Development with Flask — Request and Response

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

The Request Object

We can get data from the request object.

To get form data, we can write:

from flask import Flask, request
app = Flask(__name__)

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        if 'username' in request.form and 'password' in request.form:
            return '%s:%s' % (
                request.form['username'],
                request.form['password']
            )
        else:
            return 'Invalid username/password'

We check if 'username' and 'password' keys are in request.form .

request.form has the form data key-value pairs.

If they’re both present when we make the POST request to http://127.0.0.1:5000/login, then we return the username and password combined as the response.

Otherwise, we return ‘Invalid username/password’ .

Alternatively, we can write:

from flask import Flask, request
app = Flask(__name__)

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        username = request.args.get('username', '')
        password = request.args.get('password', '')
        if username != '' and password != '':
            return '%s:%s' % (
                username,
                password
            )
        else:
            return 'Invalid username/password'

We call request.args.get to get the value with the given form data key.

The 2nd argument is the default value.

So we can check username and password against an empty string instead to see if they have a value or not.

File Uploads

We can accept file uploads with Flask.

For example, we can write:

from flask import Flask, request
from werkzeug.utils import secure_filename
app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('./uploads/%s' % (secure_filename(f.filename)))
        return 'file uploaded'

to add the upload route.

We check the upload_file function for the route.

Then we check if the method of the request is 'POST' .

If it is, then we get the file from request.files .

Then we save the file with f.save and the path to save to.

secure_filename creates an escaped file name.

f.filename has the file name of the file that’s sent with the request.

Cookies

We can get the cookies from the request with the request.cookies.get method.

For example, we can write:

from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def index():
    username = request.cookies.get('username')
    return username

Then when we add the Cookie request header with the value username=foo when we make a GET request to http://127.0.0.1:5000/, then we get the cookie with the key username with request.cookies.get .

It should return 'foo' for username , so that’s what we see in the response body.

Also, we can send cookies with the response.

To do that, we write:

from flask import Flask, make_response, render_template
app = Flask(__name__)

@app.route('/')
def index():
    resp = make_response(render_template('index.html'))
    resp.set_cookie('username', 'the username')
    return resp

We call resp.set_cookie with the key and value of the cookie.

Then we return the response.

Conclusion

We can get request data and send cookie responses with Flask.

Categories
Flask

Python Web Development with Flask — Routes and Templates

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Unique URLs / Redirection Behavior

Adding a trailing slash to the URL will get us to access to the URL with our without a trailing slash.

For example, if we write:

from flask import Flask
app = Flask(__name__)

@app.route('/foo/')
def projects():
    return 'The foo page'

@app.route('/bar')
def about():
    return 'The bar page'

We only see ‘The bar page’ when we go to http://localhost:5000/bar.

On the other hand, if we go to http://localhost:5000/foo or http://localhost:5000/foo/, we see ‘The foo page’.

URL Building

We can use the url_for function to show the full URL of each route.

For example, we can write:

from flask import Flask, url_for
from markupsafe import escape

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}'s profile'.format(escape(username))

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='Jane Smith'))

Then in the with block, we print the full paths created from the routes.

We see:

/
/login
/login?next=%2F
/user/Jane%20Smith

url_for('index') returns ‘/‘.

url_for(‘login’) returns '/login' .

url_for(‘login’, next=’/’) returns ‘/login?next=%2F’ .

And url_for(‘profile’, username=’Jane Smith’) returns /user/Jane%20Smith .

We just pass in the function name into url_for as a string, and we get back the URL constructed from it.

HTTP Methods

A route function can take requests made with different HTTP methods.

We can restrict this with the methods parameter we pass into @app.route .

For example, we can write:

from flask import request, Flask
app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'logged in'
    else:
        return 'login form'

We set the methods parameter to the [‘GET’, ‘POST’] to restrict the function to only accept GET and POST requests.

Then we can check the request method with the request.method property.

So if we make a POST request to http://127.0.0.1:5000/login, we get ‘logged in‘ returned.

And if we make a GET request to the same URL, we get ‘login form‘ returned.

Static Files

We can serve static files with Flask.

To do that, we write:

app.py

from flask import Flask, url_for
app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello world'

with app.test_request_context():
    print(url_for('static', filename='style.css'))

static/style.css

body {
    font-weight: bold;
}

We print the path to the style.css static file in the static folder with the url_for function.

When we go to http://localhost:5000/static/style.css in the browser, we should see:

body {
    font-weight: bold;
}

displayed.

Rendering Templates

To render HTML output, we‘ve to render the content in a template.

To do that, we can use tyhe render_template function by writing:

app.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

templates/hello.html

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

We added a route that optionally takes the name parameter.

Then we call render_template with the path of the template in the templates folder.

Then we pass the variables we want to render into the subsequent arguments.

In hello.html , we check if the name variable is present, if it is, then we display the first message with the name ‘s value.

If we go to http://localhost:5000/hello/james, we see Hello james! displayed.

Otherwise, if we go to http://localhost:5000/hello, we see Hello, world.

Conclusion

We add static files and render templates with Flask.

Categories
Flask

Getting Started with Python Web Development with Flask

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Create the Project

First, we need to install Python 3 if it’s not installed already.

It comes with scripts to create a virtual environment so we don’t have to install anything else.

We can create a project by running:

$ mkdir flask-app
$ cd flask-app
$ python3 -m venv venv

on Linux.

We create the project folder and the virtual environment.

On Windows, we create the flask-app project folder and inside it, we run:

$ py -3 -m venv venv

to create the virtual environment.

Activate the Environment

We then activate the virtual environment.

To do that, we run:

$ . venv/bin/activate

in the project folder in Linux.

On Windows, we run:

> venvScriptsactivate

to do the same thing.

Install Flask

Once we install the virtual environment, we run:

$ pip install Flask

to install the Flask package.

A Minimal App

Now in the flask-app project folder, we create app.py and write:

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

to create a hello world app.

Flask(__name__) creates the Flask app.

@app.route is a decorator to add the route.

We return our response to as text in the hello_world function.

Then to run our app, we run:

$ export FLASK_APP=app.py
$ flask run

to run our app on Linux.

On Windows, we run:

> set FLASK_APP=app.py
> python -m flask run

to set the FLASK_APP environment variable and run our app.

The FLASK_APP environment variable should be set to the file name of the entry point.

Now we can go to http://127.0.0.1:5000/ in the browser and see ‘hello world’ displayed on the screen.

Debug Mode

We can turn on debug mode by setting the FLASK_END environment variable to development .

We can run:

export FLASK_ENV=development

to do that on Linux.

On Windows, we run:

set FLASK_ENV=development

to do the same thing.

Routing

We can add more than one route into our app.

For example, we can write:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Welcome'

@app.route('/hello')
def hello():
    return 'Hello, World'

Then when we go to http://127.0.0.1:5000/, we see ‘Welcome’.

And when we go to http://127.0.0.1:5000/hello, we see ‘Hello, World’.

Routing with Variables

We can make our routes more useful with variables.

For example, we can write:

from flask import Flask
from markupsafe import escape
app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    return 'User %s' % escape(username)

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post %d' % post_id

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    return 'Subpath %s' % escape(subpath)

to create an app with routes that take route parameters.

<username> is the URL parameter placeholder.

We can access it with the username parameter.

escape escapes the URL parameter so we can use it safely.

We specified the data type it takes with the int and path substrings.

int is an integer. path is a path string.

So if we go to http://localhost:5000/path/foo/bar, we get ‘Subpath foo/bar’.

And if we go to http://localhost:5000/post/2, we get ‘Post 2’.

And if we go to http://localhost:5000/user/foo, we get ‘User foo’.

We can specify the following types:

  • string — accepts any text without a slash (default)
  • int — accepts positive integers
  • float — accepts positive floating-point values
  • path — like string but also accepts slashes
  • uuid — accepts UUID strings

Conclusion

We can create simple apps with ease with Flask.

Categories
Vue Ionic

Mobile Development with Ionic and Vue — Footer, Button Group, and Text

If we know how to create Vue web apps but want to develop mobile apps, we can use the Ionic framework.

In this article, we’ll look at how to get started with mobile development with the Ionic framework with Vue.

Footer

We can add a footer with Ionic Vue.

To do that, we use the ion-footer component:

<template>
  <ion-page>
    <ion-content></ion-content>
    <ion-footer>
      <ion-toolbar>
        <ion-title>Footer</ion-title>
      </ion-toolbar>
    </ion-footer>
  </ion-page>
</template>

<script lang='ts'>
import {
  IonContent,
  IonFooter,
  IonTitle,
  IonToolbar,
  IonPage,
} from "@ionic/vue";
import { defineComponent } from "vue";

export default defineComponent({
  components: { IonContent, IonFooter, IonTitle, IonToolbar, IonPage },
});
</script>

We can also add one with no border:

<template>
  <ion-page>
    <ion-content></ion-content>
    <ion-footer class="ion-no-border">
      <ion-toolbar>
        <ion-title>Footer - No Border</ion-title>
      </ion-toolbar>
    </ion-footer>
  </ion-page>
</template>

<script lang='ts'>
import {
  IonContent,
  IonFooter,
  IonTitle,
  IonToolbar,
  IonPage,
} from "@ionic/vue";
import { defineComponent } from "vue";

export default defineComponent({
  components: { IonContent, IonFooter, IonTitle, IonToolbar, IonPage },
});
</script>

Then ion-content component holds the content on top.

The ion-title component has the title for the footer.

Button Group

We can add button groups with the ion-buttons component.

For example, we can write:

<template>
  <ion-page>
    <ion-toolbar>
      <ion-buttons slot="primary">
        <ion-button @click="clickedStar()">
          <ion-icon slot="icon-only" name="star"></ion-icon>
        </ion-button>
      </ion-buttons>
      <ion-title>Right side menu toggle</ion-title>
      <ion-buttons slot="end">
        <ion-menu-button auto-hide="false"></ion-menu-button>
      </ion-buttons>
    </ion-toolbar>
  </ion-page>
</template>

<script>
import {
  IonBackButton,
  IonButton,
  IonButtons,
  IonIcon,
  IonMenuButton,
  IonTitle,
  IonToolbar,
  IonPage
} from "@ionic/vue";
import { personCircle, search } from "ionicons/icons";
import { defineComponent } from "vue";

export default defineComponent({
  components: {
    IonBackButton,
    IonButton,
    IonButtons,
    IonIcon,
    IonMenuButton,
    IonTitle,
    IonToolbar,
    IonPage
  },
  setup() {
    const clickedStar = () => {
      console.log("Star clicked!");
    };
    return { personCircle, search, clickedStar };
  },
});
</script>

to add the ion-buttons component.

Then we can add the ion-button components inside to add the buttons.

ion-button emits the click event so we can run something when we click it.

Text

We can add text into our app with the ion-text component.

For example, we can write:

<template>
  <ion-page>
    <ion-text color="danger">
      <h4>H4: The quick brown fox jumps over the lazy dog</h4>
    </ion-text>
  </ion-page>
</template>

<script>
import { IonPage, IonText } from "@ionic/vue";
import { defineComponent } from "vue";

export default defineComponent({
  components: {
    IonPage,
    IonText,
  },
});
</script>

to add the text.

color has the color of the text.

Conclusion

We can add a footer, button group and text with Ionic Vue.

Categories
Vue Ionic

Mobile Development with Ionic and Vue — Toggle, Toolbar, and Header

If we know how to create Vue web apps but want to develop mobile apps, we can use the Ionic framework.

In this article, we’ll look at how to get started with mobile development with the Ionic framework with Vue.

Toggle Switches

We can add toggle switches with the ion-toggle component.

For example, we can add switches with various colors:

<template>
  <div>
    <ion-toggle color="primary"></ion-toggle>
    <ion-toggle color="secondary"></ion-toggle>
    <ion-toggle color="danger"></ion-toggle>
    <ion-toggle color="light"></ion-toggle>
    <ion-toggle color="dark"></ion-toggle>
  </div>
</template>

<script>
import { IonLabel, IonList, IonItem, IonToggle } from "@ionic/vue";
import { defineComponent, ref, vue } from "vue";

export default defineComponent({
  components: { IonLabel, IonList, IonItem, IonToggle }
});
</script>

Also, we can write:

<template>
  <ion-item>
    <ion-label>Mushrooms</ion-label>
    <ion-toggle
      @ionChange="checked.value = !checked.value"
      value="mushrooms"
      :checked="checked"
    >
    </ion-toggle>
  </ion-item>
</template>

<script>
import { IonLabel, IonList, IonItem, IonToggle } from "@ionic/vue";
import { defineComponent, ref, vue } from "vue";

export default defineComponent({
  components: { IonLabel, IonList, IonItem, IonToggle },
  setup() {
    const checked = ref(false);
    return { checked };
  },
});
</script>

to set a reactive property when we toggle the value.

Toolbar

We can add a toolbar with the ion-toolbar component.

For instance, we can write:

<template>
  <ion-toolbar color="dark">
    <ion-buttons slot="secondary">
      <ion-button>
        <ion-icon slot="icon-only" :icon="personCircle"></ion-icon>
      </ion-button>
      <ion-button>
        <ion-icon slot="icon-only" :icon="search"></ion-icon>
      </ion-button>
    </ion-buttons>
    <ion-buttons slot="primary">
      <ion-button color="danger">
        <ion-icon
          slot="icon-only"
          :ios="ellipsisHorizontal"
          :md="ellipsisVertical"
        ></ion-icon>
      </ion-button>
    </ion-buttons>
    <ion-title>Dark Toolbar</ion-title>
  </ion-toolbar>
</template>

<script>
import {
  IonButton,
  IonButtons,
  IonIcon,
  IonTitle,
  IonToolbar,
} from "@ionic/vue";
import {
  ellipsisHorizontal,
  ellipsisVertical,
  helpCircle,
  personCircle,
  search,
  star,
} from "ionicons/icons";
import { defineComponent } from "vue";

export default defineComponent({
  components: {
    IonButton,
    IonButtons,
    IonIcon,
    IonTitle,
    IonToolbar,
  },
  setup() {
    return {
      ellipsisHorizontal,
      ellipsisVertical,
      helpCircle,
      personCircle,
      search,
      star,
    };
  },
});
</script>

to add a dark toolbar with some buttons inside it.

ion-title has the title of the toolbar, which is displayed on the left side.

Header

We can add a header with various styles.

For example, we can write:

<template>
  <ion-header>
    <ion-toolbar>
      <ion-buttons slot="start">
        <ion-back-button></ion-back-button>
      </ion-buttons>
      <ion-title>Navigation Bar</ion-title>
    </ion-toolbar>

    <ion-toolbar>
      <ion-title>Subheader</ion-title>
    </ion-toolbar>
  </ion-header>

  <!-- Header without a border -->
  <ion-header class="ion-no-border">
    <ion-toolbar>
      <ion-title>Header - No Border</ion-title>
    </ion-toolbar>
  </ion-header>
</template>

<script>
import {
  IonBackButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonTitle,
  IonToolbar
} from '@ionic/vue';
import { defineComponent } from 'vue';

export default defineComponent({
  components: {
    IonBackButton,
    IonButtons,
    IonContent,
    IonHeader,
    IonTitle,
    IonToolbar
  }
});
</script>

to add the header with a toolbar inside.

We can add the ion-no-border class to remove the border from the header.

Conclusion

We can add a toggle switch, toolbar and header with Ionic Vue.