Flask - Redirecting

Flask References:



Comments and notes:


Screen shot


Code:

"""
File: lab6flask03.py
Date: Oct 4, 2021
Author: Nicholas Duchon
Purpose: Exploring redirect and url_for
"""

from flask import Flask
from flask import request, redirect, url_for

TITLE = "Nicholas Duchon page"

# time:
import time
def my_curtime () :
  return time.asctime(time.localtime(time.time()))

# st and mtime should be given values as this page format is called
page = \
"""
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>One</title>
    </head>
    <body>
        <h1>Page: {st}</h1>
        <h2>time: {mtime}</h2>
        <form action="/" method="post">
            <input value="to /" type="submit">
            <p>
            <input value="redirect ('/b')" name="redirect b" type="submit">
            </p>
            <p>
            <input value="redirect.url_for ('replyA')" name="redirect replyA" type="submit">
            </p>
            <p>
            <input value="action: /a" formaction="a" type="submit">
            </p>
            <p>
            <input value="action: /b" formaction="/b" type="submit">
            </p>
            <p>
            <input value="redirect.url_for ('replyB')" name="redirect replyB" type="submit">
            </p>
        </form>
    </body>
</html>
""".format

app = Flask (__name__)

@app.route ("/", methods=['GET', 'POST'])
def reply (p="default") :
   if request.method == 'POST':
      w1 = request.form
      if 'redirect b' in w1.keys():
        return redirect ("/b")
      if 'redirect replyA' in w1.keys():
        return redirect(url_for ("replyA"))
      if 'redirect replyB' in w1.keys():
        return redirect(url_for ("replyB", arg="using url"))
   return page (st=p, mtime=my_curtime())

@app.route ("/a", methods=['GET', 'POST'])
def replyA (p=" this is page a") :
    return page (st=p, mtime=my_curtime())

@app.route ("/b", methods=['GET', 'POST'])
def replyB (p="PAGE B") :
    ag = request.args # GET method
    if 'arg' in ag.keys():
        p = ag.get('arg')
    return page (st=p, mtime=my_curtime())

if __name__ == "__main__":
   app.run (debug=True)





(end)