How to set a variable with pressing a button on an html file to the flask server route

2.8k views Asked by At

I've become a bit confused in the middle of this, hope you can help me,

I have a text file similar to the one below:

./Video/SetUp
./Video/NewRecordings
./Video/NewRecordings/20160113_151920
./Video/Back Up
./Video/Back Up/FirstLecDraft
./Video/Back Up/FirstTalk

I use the python script below (thanks to Dominate) to populate a html file using the List text file mentioned above:

import dominate
from dominate.tags import *

doc = dominate.document(title='Dominate your HTML')

with doc.head:
    link(rel='stylesheet', href='style.css')
    script(type='text/javascript', src='script.js')

with doc:
    with div():
        with open('List') as f:
            for line in f:
                li(input(line.title(), type='submit', value='%s' % line,     onclick='self.location.href=\'http://127.0.0.1:5000/{This must be the same as "value" part}\''))

    with div():
        attr(cls='body')

print doc

First question: How to pass the value of the value field to the rest of the path on onclick?

The result must be something like this:

<input href="" onclick="self.location.href='http://127.0.0.1:5000/cameradump/2016-01-21" type="submit" value="./cameradump/2016-01-21">

and respectively another values for another buttons.

as you can see, the rest of the onclick path after :5000/must be exactly the same as the value field.

Second question: How can I pass this to the route on flasks' main.py file? (e.g when the user presses each button, the value of that button must be set to the route dynamically)

main.py is like this for now:

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

@app.route("/{value must be passed here}")
def index():
    return render_template('index.html')
 ...

but it should be like below if the user presses the button /cameradump/2016-01-21:

...
@app.route("/cameradump/2016-01-21")
def index():
return render_template('index.html')
...

or another value according to the button which was pressed.

1

There are 1 answers

0
furas On BEST ANSWER

First:

Do the same way as you do with value - use %

onclick='self.location.href="http://127.0.0.1:5000/%s"' % date

If you can't have "2016-01-21" in file "List" but you have "/cameradump/2016-01-21" then you can split it (using "/") and get last element - date.

# `line` is `"/cameradump/2016-01-21"`

data = line.split('/')[-1]

Second:

Read doc about routing

You can use variables in route to get date

@app.route("/cameradump/<date>")
def index(date):
    print("Date:", date)
    return render_template('index.html')