Python - Can't import with_statement from __future__ - python

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

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.

UnitTest Case for Flask application

Writting UniTTest For Flask Application
I have a simple Flask Application below , flask application will work perfectly fine without any issues
import sys , os , os.path , time , datetime , json , logging, warnings
from os import listdir
from os.path import isfile, join
from flask_wtf.csrf import CSRFProtect
from flask import Flask
from flask import render_template
from flask import request
from datetime import datetime
from logging import FileHandler
from logging import Formatter
# --> Required Host and Env
_cloudhost='dev.net'
_cloudenv='dev'
_portNumber=4444
#CRF Compliant / (.)
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)
#app.route('/')
#app.route('/index')
def index():
project = "CFTP - TBRP & TBLP "
framework = "Publish Framework"
version = '0.1'
hostname = os.popen("echo $(hostname)").read().split('\n')[0]
return render_template('index.html', title=project , description=f'{project} : {framework} v - {version}' , hostname=hostname , logFile=readlogs(), get_env=_cloudenv)
app.run(host=_cloudhost, port=_portNumber)
UnitTest Function . I am struggling to understand on how i can create unit test cases for flask application. Inside my unittest file which i created , i was wondering if i am doing this right .
1 -> To test the csrf if that i included above and also on how i can test my index page can result as pass
test_flask.py
import unittest , sys , tempfile, os , json , shutil
from unittest import mock
from subprocess import Popen, PIPE
import logging
with mock.patch.dict(os.environ, {'PROJECT_FOLDER':'CitiFTP Reports','RPM_ENVIRONMENT': 'DEV', 'HOST_NAME': 'sd-nzvp-czog.nam.nsroot.net', 'USER': 'citiftptabhyper','TABLEAU_PUBLISH_TYPE':'TABCMD','TABCMD_PATH':'/home/citiftptabhyper/tabcmd','CYBERARK_TYPE':'DYNAMIC','JOB_TYPE':'workbook_TP','JOB_FILE':'publish_workbook_TP','RESTAPI_LOG_TYPE':'TP'}):
sys.path.insert(2, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/src')
sys.path.insert(1, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/app')
import env_conf as conf
import run_flask as flk_app
from run_flask import app
class test_tbrp_case(unittest.TestCase):
def setUp(self):
self.ctx = app.app_context()
self.ctx.push()
self.client = app.test_client()
def tearDown(self):
self.ctx.pop()
def test_home(self): ## Fail
response = self.client.post("/index", data={"title": "CFTP - TBRP & TBLP "})
assert response.status_code == 200
## test flask port used -- PASS
def test_port(self):
self.assertEqual(flk_app._portNumber,4444)
## Test host is returning the same value -- PASS
def test_host(self):
self.assertEqual(flk_app._cloudhost,conf.FLASK_CONFIGURATION.get('ENV_URL'))
def test_csrf(self):
pass
if __name__=='__main__':
unittest.main()

Logging; ImportError: cannot import name 'get_logger' from 'logger'

I've got a Python script from a friend who is not in available at the moment.
Unfortunately i am not able run it.
Error:
ImportError: cannot import name 'get_logger' from 'logger' (C:\Users\MyName\AppData\Local\Programs\Python\Python311\Lib\site-packages\logger\__init__.py)
I can locate the file __init__.py at the mentioned path.
Part of the script which causes this error:
import time
import sys
import requests
from bs4 import BeautifulSoup
import pandas as pd
from requests.api import post
import os
import traceback
from logger import get_logger #<----- Error
from datetime import date
dir_path = os.path.dirname(os.path.realpath(__file__))
logging = get_logger(dir_path)
logger = logging.getLogger(__name__)
logger = logging.getLogger()
[...]
Code of __init__.py:
import logging
import logging.config
import os
import sys
import types
logging.getLogger('paramiko').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
config_file = os.path.join(os.path.dirname(__file__), 'logging.conf')
logging.config.fileConfig(config_file, disable_existing_loggers=False)
logger = logging.getLogger()
def error(self, msg, *args, **kwargs):
self.error(msg, *args, **kwargs)
sys.exit(1)
logger.interrupt = types.MethodType(error, logger)
logger.info = logger.info
logger.warn = logger.warn
I hope you guys can help me to solve this issue.
Thanks!
What i tried
Googled ImportError: cannot import name 'get_logger' from 'logger' - Answere was based on another issue (ImportError: cannot import name 'getLogger')
Tried to directly import logging instead of logger
No idea what else i should try since i usually do not develope (Hi from sales)

Dash getting session object variables throws the dreaded Runtime Error

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.

ImportError: No module named control

I have a celery app, my files like this:
/fetcher.py
/mirad
celery.py
fetcher_tasks.py
in celery.py i was import fetcher_tasks.py
and in fetcher.py i call a task from fetcher_tasks.py
i want to import celery.control in fetcher.py but i can't do it, how i can do this work?
this is a part of my fetcher code:
from __future__ import absolute_import
import mirad.fetcher_tasks as tasks
from mirad.models.models import SourceModel
from mirad.settings import *
from mirad.celery.control import inspect
parse_feed_tasks = list()
def fetch():
for source in SourceModel.objects(active=True):
a = tasks.parse_feed.delay(source)
Looks like you mix celery.py in your project which is used to start Celery app with celery package from which you can import necessery functions.
You should import inspect function from celery.task.control package.
from __future__ import absolute_import
import mirad.fetcher_tasks as tasks
from mirad.models.models import SourceModel
from mirad.settings import *
from celery.task.control import inspect
parse_feed_tasks = list()
def fetch():
for source in SourceModel.objects(active=True):
a = tasks.parse_feed.delay(source)

Categories