Forums

N00b question about python with flask...

Hello, I have a very simple question I hope. I know python, but I'm brand new to using it with flask on the web. My flask_app.py has:

from flask import Flask
from homepage import homepage
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def a():
    content = homepage()
    return content

... and my homepage.py has:

from flask import request
form = """
    <form method="post" action="/">What is your name?<input type="text" name="name"><input type="submit"></form><br>
"""
def homepage():
    name = ""
    if request.method == 'POST':
        name = request.form['name']
    name = "Your name is " + name + "."
    return form + name

My question is, how can I store the variable name in memory without: 1. Creating a database 2. Passing it with a <form> post/get

Is there any way to store them globally even after clicking through a link to another .py file.

Maybe cookies? Maybe something simpler that just exists in Flask?

Thank you!

What do you want to do with that variable in the memory?

I want to be able to reuse it. For example, I'm making a tictactoe game, where after each move, I need to remember the state of the board, just a pythin list variable. I'd like to keep it in the memory every time the page refreshes.

You’ll have to either store that in a database or in a session variable. Otherwise, that variable will be reinitialized every time you restart your app.

Try to look at some tutorials that talk about flask sessions, it’s extremely easy. The downside is that the data will be stored on the client (your user’s computer), so if they clear their cookies or use a separate device, the data will be gone. Also, when you restart your server, the previous session cookies will expire (though that depends).

Using a database might sound daunting, but I assure you it’s easy. Look up some tutorials for flask + sqlite + sqlalchemy, it’ll bring your flask app to the next level. Quite frankly, any useful web app will need a database.

You may also consider doing all of that in the frontend javascript code. See the React tutorial that is exactly about tictactoe game https://reactjs.org/tutorial/tutorial.html

Thank you. I would like to concentrate on python only for now. Thank you for the JS link, I'll save it.

I just looked up session variables in Flask, and actually that would work best for me. I could even use them to add ability to play tic-tac-toe across the Internet. Later I can switch to using database.

Thank you, I'm just going to play with this https://pythonbasics.org/flask-sessions/