#πŸ”’ Need flask help.

25 messages Β· Page 1 of 1 (latest)

sullen juniper
#

Context: using vercel and pythonanywhere to deploy. In backend, i have this endpoint:

@leaveManager.route('/postLeaveRq',methods=['POST'])
def PostLeave():

    if 'employeeId' not in session or 'id' not in session:
        return jsonify({"status":"error"}),401
    
    empId = session.get("employeeId")
    auth_id = session.get("id")

    data = rq.get_json()

    name = data.get('name')
    department = data.get('department')
    startdate = data.get('startDate')
    enddate = data.get('endDate')
    reason = data.get('reason')
    dateSubmitted = data.get('dateSubmitted')
    try:
        start = datetime.strptime(startdate, "%Y-%m-%d").date()
        end = datetime.strptime(enddate, "%Y-%m-%d").date()
        
        if reason == "":
            return jsonify({"message":"Reason not given. ","status":"reason not provided"})
        
        if end < start:
            return jsonify({"message":"Invalid structure. ","status":"datetime compare error"})

        status = leavehandler.createLeaveRq(auth_id=auth_id,name=name,department=department,startdate=startdate,enddate=enddate,reason=reason,dateSubmitted=dateSubmitted,empId=empId)
        notifManager.insert_notification(message=f"A leave request has been issued.",adminOnly=True)
        return jsonify({"message":"Leave request sent successfully.","status":status})
        
    except Exception as e:
        print(e)
        return jsonify({"error":f"{e}"})```

Whats the problem i cannot debug:
This endpoint returns successfull fetch in local machine. 200 status code.

But in production it always returns 401 regardless of if conditions.

In frontend, console.error does not print.

const response = await fetch(${API_BASE_URL}/postLeaveRq, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(leaveData),
});
const data = await response.json();
console.error(data);```

What to fix: production errors

rare daggerBOT
#

@sullen juniper

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

brave harbor
sullen juniper
#

yes this is after the login phase.

brave harbor
sullen juniper
#

flask sessions..
Here :

session['permission'] = permission
                session['role'] = role 
                session['name'] = name 
                session['email'] = email
                session['employeeId'] = employeeId
                session['id'] = str(id) 
                session['status'] = "Logged In"

And from endpoints, i use session.get

brave harbor
#

Effectively its just this line

   if 'employeeId' not in session or 'id' not in session:
        return jsonify({"status":"error"}),401
#

And your frontend only does this:

const response = await fetch(`${API_BASE_URL}/postLeaveRq`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(leaveData),
      });
      const data = await response.json();
console.error(data);
brave harbor
sullen juniper
#

yes. debug statements do print sessions dictionary. i will share local code run demo

brave harbor
sullen juniper
#

yes. i use localstorage. but it only sets it once.

const response = await fetch(`${API_BASE_URL}/Login`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });

      const data = await response.json();
      //console.log("πŸ” Login response:", data);

      if (!data || data.Permission === 0) {
        setMessage({ type: "Error", text: data.message || "Invalid credentials." });
        return;
      }
      
const userSession = {
        employeeId: data.employeeId,
        auth_id:    data.id,
        name:       data.name,
        email:      data.email,
        role:       data.role,
        permission: data.Permission,
        status:     data.status,
      };
      localStorage.setItem("MySession", JSON.stringify(userSession));```
brave harbor
sullen juniper
#

hmm yes i did.. first time from login post request. but then i only use backend to check

brave harbor
#

Share the full error message

#

@sullen juniper ?

sullen juniper
#

yes i am here.. wait a minute

#

Failed to load resource: the server responded with a status of 401 (UNAUTHORIZED)Understand this error
index-BrBJ_iga.js:24 Data passed:[object Object]
index-BrBJ_iga.js:24 Leave data:[object Object]

When i click the endpoint, it shows "status":"error"

brave harbor
sullen juniper
#

is the issue related to cookies ?

brave harbor
sullen juniper
#

Update: flask_secret_key is used from env file. in my wsgi file, i use:

os.environ['SESSION_COOKIE_SAMESITE'] = 'None'
os.environ['SESSION_COOKIE_SECURE'] = 'True'
os.environ['FLASK_SECRET_KEY'] = ''

In my app.py (main server file) i use:

app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY")

app.config['SESSION_COOKIE_SAMESITE'] = 'None'
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True

rare daggerBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.