Malakaman Malakaman - 1 year ago 180
HTML Question

Using request args in Flask for a variable URL

First time Flask user here--just read the pocoo guide
My goal is to run a Flask app that will be given a URL of this form where the ids vary:


and return a simple page outputting something like "First id = 123, second id = 456, third id = 789"

I run this script, and when hardcoding in an example url I cannot get request args to return anything but None. I have tried formatting the int as a string and different things like that--in no circumstances can I get request args to work.

import os
import json
from flask import Flask, request, render_template

app = Flask(__name__)

def main():
return "on main home page"

def Longword():
user = request.args.get('gameid')
return "got hardcode %d" % gameid

My second issue, which will be tackled after I can get request args going, is that I cannot configure route() in such a way to handle variable URLS. I am only able to load pages by hardcoding them into route. I made a separate attempt to do this using sessions but was equally unsuccessful--if anyone has a nice way to do this with sessions that would be greatly appreciated. Many thanks

Answer Source

You need route('/longword/') without arguments after ?

Then you can run with arguments after ?


In function you can get this arguments using request.args.get()

def longword():

    gid = request.args.get('gameid')
    pid = request.args.get('playerid')

    return "GID: %s  PID: %s" % (gid, pid)

And last thing: arguments are strings even if you send numbers so you need %s instead of %d

BTW: you can run this url also without some argument ie.


and you can set default value with request.args.get()

    gid = request.args.get('gameid', 'default gameid')
    pid = request.args.get('playerid', 'default playerid')

If you don't use own default value then request.args.get() will use None

    gid = request.args.get('gameid')
    pid = request.args.get('playerid')

    if not gid or not pid:
        return "You forgot gameid or playerid"

    return "GID: %s  PID: %s" % (gid, pid)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download