Dash getting session object variables throws the dreaded Runtime Error - python

I have searched far and wide, including SO, for a possible suggestion to this error.
Running a dash app on a server that needs to grab information from the session variable.
This is the beginning code of the dash app page that eventually errors out.
import dash
import dash_core_components as dcc
import dash_html_components as html
from numpy.lib.function_base import select
import plotly.express as px
import pandas as pd
import dash_bootstrap_components as dbc
from dash_core_components.RadioItems import RadioItems
import csv
import numpy as np
pd.options.mode.chained_assignment = None # default='warn'
from datetime import datetime
import time
from datetime import date
now = pd.to_datetime('now')
#Dash Stuff
from dash.dependencies import Input, Output, State
import dash_table
import pyodbc
from flask import request, session
from app import app, server
connectionStr = server.config.get('DATABASE_CONNECTION_STRING', None)
conn = pyodbc.connect(connectionStr)
#print(session.get('udata'))
When I run this code via my index.py file, I get the following error.
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
And, so, I have read the documentation, as best I can determine which of the Flask documentation this error refers. The request and context and application context documentation. You will notice, I am not using a request call at all, which makes the error confusing.
Anyone with dash apps that have to inherit session variables to show the appropriate user data would be a big help here.

Related

How to debug VSCODE python using local packages

import logging
import sys
import os
from LoggingHelper.main import LoggingHelper <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from LoggingHelper.models import logDataclass as ldc <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from .configs.project_configs import *
kafka_config = {}
from fastapi import FastAPI, Request <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from fastapi.responses import JSONResponse <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import fastapi <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import azure.functions as func <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import nest_asyncio
from starlette.middleware import Middleware <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from starlette.middleware.cors import CORSMiddleware <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
nest_asyncio.apply()
from TSAuthHelper import FastAPIAuthHelper <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import json
import os
import time
import traceback
import pickle
I have a local library/package in ".python_packages\lib\site-packages" called "LoggingHelper", "fastapi", "starlette/middleware", etc. But I can't compile those in VSCODE.
They work just fine if I publish them all to Azure Functions, but not locally. I need to debug them locally on my VSCODE.
I have been trying to read everything I can, change the interpreter, etc. But I'm not a developer and need some guidance.
from .python_packages/fastapi import FastAPI
from fullpath/.python_packages/fastapi import FastAPI
nothing works.
When running locally you may need to specify the major version of Python you intend to use. Normally on Linux the first line of a Python3 program would be something like:
#!/usr/bin/python3
import os
...
Then before importing modules that are in an unusual location you might need to add a line:
sys.path.append("/fullpath/to/custom/modules/dir")
then you should be able to import modules that are in that directory.

Python, fastAPI, uvicorn - Error loading ASGI app. Could not import module "main"

I am having trouble with getting uvicorn to start. I am very new to python and fastapi so I am assuming I have doing something very silly.
I have isolated the problem to being in my api_router.py file
from fastapi import APIRouter
from API.endpoints import user_endpoints
api_router = APIRouter()
api_router.include_router(user_endpoints, prefix="/user", tags=["User"])
When I comment out from API.endpoints import user_endpoints and
api_router.include_router(user_endpoints, prefix="/user", tags=["User"]), the error does not occur. Am I trying to import my user_endpoints.py file incorrectly? I have attached an image of the directory structure.
user_endpoints.py looks like this:
from fastapi.routing import APIRouter
from typing import Optional, List
from API.schema.user import User
from models.user import Users
from main import db
router = APIRouter
#router.get('/users', response_model=List[User], status_code=200)
def get_all_users():
users=db.query(Users).all()
return users
#router.get('/users/{user_id}')
def get_user(user_id):
pass
#router.post('/users')
def create_user():
pass
#router.put('/users/{user_id}')
def update_user(user_id):
pass
#router.delete('/users/{user_id}')
def delete_user(user_id):
pass
Any help with this would be greatly appreciated.
Thanks,
Greg
I think it's talking about the current working directory of your terminal, when you feed it uvicorn main:app ... not being able to find main. Make your terminal's working directory same as main.py

Clean way to import methods ( sep files ) into a class defined in __init__.py

I can call objects out of a method in a fashion that explicitly defines an endpoint ( this REST API is really a collection of RESTful endpoints ):
ie:
import symphony
pod_object = symphony.Pod(self.__uri__, self.__session__, self.__keymngr__)
agent_object = symphony.Agent(self.__uri__, self.__session__, self.__keymngr__)
agent.userid_by_email(email)
pod.send_message(userid, message)
This would be the __init__.py for a Module symphony
from .Agent import Agent
from .Auth import Auth
from .Config import Config
from .Crypt import Crypt
from .Mml import Mml
from .Pod import Pod
from .RESTful import RESTful
This would be the __init__.py for a Class Pod in Module symphony
class Pod():
# basic methods
from .base import sessioninfo
# user methods
from .users import get_userid_by_email
from .users import get_user_id_by_user
from .users import user_feature_update
from .users import search_user
# streams methods
from .streams import adduser_to_stream
from .streams import create_stream
from .streams import create_stream_ni
from .streams import create_room
from .streams import update_room
# group methods
from .groups import ib_group_list
from .groups import ib_group_member_list
from .groups import ib_group_member_add
from .groups import ib_group_policy_list
# connection methods
from .connections import list_connections
from .connections import connection_status
from .connections import accept_connection
from .connections import create_connection
def __init__(self, url, session, keymngr):
self.__url__ = url
self.__session__ = session
self.__keymngr__ = keymngr
self.__rest__ = symphony.RESTful(self.__url__, self.__session__, self.__keymngr__)
I have something like this. And I really like this.. Cause I can then have many classes divided into Dir structures with many methods divided into many files. Clean simple code. All registering to a module later on down the line.
But I have to individually register methods, instead of the entire file.
Is there some way to cleanly import all the methods in the files?
Python2 / 3 compatible way?
That is, well, really, ah, not all that pretty.
If your class is too big to fit in one file, it's just too big and should be divided into several classes.
The obvious solution is to create several base classes, one for user methods, one for stream methods, one for group methods and so on. Then have your Pod class inherit from all of them.
Without knowing more about the problem you're trying to solve it's impossible to recommend a different way to design your classes. It does feel as if you're not doing the right thing, though, even if you do get Pod to inherit from all those base classes.

Python - Can't import with_statement from __future__

Here are the other imports already in my app
import os
import sys
from google.appengine.ext.webapp import template
import cgi
import urllib
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
from django.utils import simplejson as json
from datetime import datetime
import random
import string
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import files
Everything compiles and works fine.
But when I add this import:
from __future__ import with_statement
nothing works. I go to appspot, and the page just says "server error."
How can I successfully import with_satement?
EDIT:
I I know blobstore is deprecated. with is used with blobstore. Could that be what's causing the problem? But with isn't only used with blobstore...
Try adding the import to the very top of your file (after any #!/usr/bin/python2.x statements).
from __future__ imports must occur at the beginning of the file

saving data to mongodb using pymongo

I am having an issue trying to save data to MongoDB.
I first run this python program:
import pymongo
import sys
def main():
connection = pymongo.Connection("mongodb://localhost", safe = True)
db = connection.m101
people = db.people
person = {'name':'Barack Obama', 'role':'president'}
people.insert(person)
but then, when i try to retrieve the data from the mongoshell:
> use m101
switched to db m101
> db.people.find()
returns nothing! I'm not sure what is going on. Thanks for your help.
Your code is not working because main() is never called.
Adding
if __name__ == '__main__':
main()
will execute your defined main function when executed.
You are not executing your main() function so nothing was ever executed.
Simple solution
from flask import Flask
from flask_pymongo import PyMongo
import json
import datetime
import urllib, json
from flask import jsonify
from bson.json_util import dumps
#app.route("/saveBookings", methods=['POST'])
def saveBookings():
posts = mongo.db.bookings
post = {"meetingRoom_name": "kriti_jio",
"personName": "honey",
"meetingRoom_location": "kannauj",
"book_start_time": datetime.datetime.utcnow()}
post_id = posts.insert_one(post).inserted_id
return jsonify(status="done",id=dumps(post_id),action="Data saved Succesfully",error="false");

Categories