Python Forum
Flask: Cookies for Saving User Input ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask: Cookies for Saving User Input ?
#1
Hi. I am developing a web-app which contains map api in order to let the user select his location. The following code is about this procedure;
app = Flask(__name__)
C = cookies.SimpleCookie()
C['enlem']        = 39.9215219
C['boylam']       = 32.8537929
C['UTC_Offset']   = 3
C['yukseklik']    = 0
C['lokasyon']    = "Ankara, Türkiye"
C['Adres']      = "Ankara,Türkiye"
@app.route('/Konum_Belirle', methods = ['GET','POST'])
def Konum_Belirle():
    tf = TimezoneFinder()
    utc = pytz.utc
    resp = make_response(render_template('Konum_Degistir.html'))
    if request.method == "POST":
        adres = request.form.get('Adres')
        geolocator = Nominatim(user_agent="specify_your_app_name_here", timeout=5)
        lokasyon = geolocator.geocode(adres)
        C['lokasyon'] = lokasyon
        resp.set_cookie('lokasyon',C['lokasyon'].value)
        if C['lokasyon'].value == None:
           C['lokasyon']="Adres Bulunamadı."
           resp.set_cookie('lokasyon',C['lokasyon'].value)
           C['UTC_Offset']= "Zaman dilimi bulunamadı!"
           C['enlem'] = 0
           resp.set_cookie('enlem',C['enlem'].value)
           C['boylam'] = 0
           resp.set_cookie('boylam',C['boylam'].value)
        else:
           C['enlem']=lokasyon.latitude
           resp.set_cookie('enlem',C['enlem'].value)
           C['boylam'] = lokasyon.longitude
           resp.set_cookie('boylam',C['boylam'].value)
           today = datetime.now()
           tz_target = timezone(tf.certain_timezone_at(lat=float(C['enlem'].value), lng=float(C['boylam'].value)))
           if tz_target == None:
                C['UTC_Offset']= "Zaman dilimi bulunamadı!"
           else:
                today_target = tz_target.localize(today)
                today_utc = utc.localize(today)
                C['UTC_Offset'] = (today_utc - today_target).total_seconds() / (60*60)
    enlem = request.cookies.get('enlem')
    boylam = request.cookies.get('boylam')
    lokasyon = request.cookies.get('lokasyon')
    UTC_Offset = float(C['UTC_Offset'].value)
    return render_template('Konum_Degistir.html', adres = lokasyon, enlem = enlem, boylam = boylam, yukseklik=C['yukseklik'].value\
                           UTC_Offset =  UTC_Offset)
I need to save the user location input, such that his address, and determine the latitude and longitude of his location and then save these variables into his cookies and reach it from another route function, but when I tried to save them into cookies, the request.cookies.get returns None everytime. My web-app does not contain any log-in feature. My question is how can I save this input for every individual user and reach them. Are the cookies solution for this problem or are there any other alternatives ?
Reply
#2
For any one who need to save something in cookies and gather them into another route, I found this solution;
from flask import Flask, redirect, url_for, render_template, make_response,request 

app = Flask(__name__)
@app.route('/Konum_Degistir', methods = ['GET','POST'])
def Konum_Degistir():
    if request.method == "POST":
        resp = make_response(redirect(url_for('Konum_Getir')))
        tf = TimezoneFinder()
        utc = pytz.utc
        adres = request.form['Adres']
        geolocator = Nominatim(user_agent="specify_your_app_name_here", timeout=5)
        lokasyon = geolocator.geocode(adres)
        resp.set_cookie('lokasyon',str(lokasyon))
        if lokasyon == None:
           lokasyon="Adres Bulunamadı."
           resp.set_cookie('lokasyon', str(lokasyon))
           UTC_Offset= "Zaman dilimi bulunamadı!"
           enlem = 0
           resp.set_cookie('enlem',str(enlem))
           boylam = 0
           resp.set_cookie('boylam',str(boylam))
        else:
           enlem=lokasyon.latitude
           resp.set_cookie('enlem', str(enlem))
           boylam = lokasyon.longitude
           resp.set_cookie('boylam', str(boylam))
           today = datetime.now()
           tz_target = timezone(tf.certain_timezone_at(lat=enlem, lng=boylam))
           if tz_target == None:
                UTC_Offset= "Zaman dilimi bulunamadı!"
                resp.set_cookie('UTC_Offset',str(UTC_Offset))
           else:
                today_target = tz_target.localize(today)
                today_utc = utc.localize(today)
                UTC_Offset = (today_utc - today_target).total_seconds() / (60*60)
                resp.set_cookie('UTC_Offset',str(UTC_Offset))
        return resp
    else:
        if not request.cookies.get('enlem'):
            resp = make_response(render_template('Konum_Degistir.html', enlem =0, boylam=0))
        else:
            resp = make_response(render_template('Konum_Degistir.html', enlem =request.cookies.get('enlem'),boylam = request.cookies.get('boylam')))
        return resp
@app.route('/Konum_Getir',  methods = ['GET','POST'])
def Konum_Getir():
    enlem =request.cookies.get('enlem')
    boylam = request.cookies.get('boylam')
    lokasyon = request.cookies.get('lokasyon')
    UTC_Offset = request.cookies.get('UTC_Offset')
    return render_template('Konum_Getir.html', adres = lokasyon, enlem = enlem, boylam= boylam, UTC_Offset= UTC_Offset)
In order to get the latest cookie in the same route, one can make response to redirect for the same route.
Reply
#3
Hello, I'm glad you found the solution, and thanks for coming back to share it!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python cookies vj78 2 1,456 Apr-07-2021, 09:38 AM
Last Post: Naheed
  User Input to mySQL database newbie1 3 1,808 Aug-26-2020, 10:42 AM
Last Post: newbie1
  Flask - IIS Get Windows User Name beachdogvet 0 2,276 Feb-28-2020, 12:37 PM
Last Post: beachdogvet
  Catch all cookies from any website Chuky 8 4,611 Aug-20-2019, 04:24 PM
Last Post: snippsat
  Download images generated by user input one_of_us 0 1,323 Mar-26-2019, 07:58 AM
Last Post: one_of_us
  python scraping all cookies halberdd 1 2,651 Feb-26-2019, 12:10 PM
Last Post: halberdd
  Inserting multiple cookies using python requests freshtomatoes 0 3,251 Aug-16-2018, 09:25 PM
Last Post: freshtomatoes
  Unable to load cookies with Pickle HiImNew 5 7,600 Jan-04-2018, 12:36 PM
Last Post: snippsat
  Pulling any information from a dictionary with a user input Darmanus 19 4,669 Nov-22-2017, 08:56 PM
Last Post: Larz60+
  Missing cookies in session with requests sechot 0 4,615 Oct-22-2017, 12:09 PM
Last Post: sechot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020