I am trying to setup a pyramid app to use both webtest and sqlalchemy.
If I comment out the SQLAlchemy code, the webtests run without a problem.
[Test log ] https://travis-ci.org/caffeinated-expert/frisbee/builds/91622436
Error
Traceback (most recent call last):
File "frisbee/frisbee/tests/test_cities_page.py", line 18, in setUp
app = main({})
File "frisbee/frisbee/__init__.py", line 15, in main
engine = engine_from_config(settings, 'sqlalchemy.')
File "build/bdist.macosx-10.10-x86_64/egg/sqlalchemy/engine/__init__.py", line 426, in engine_from_config
url = options.pop('url')
KeyError: 'url'
In my main init file, if I comment out the sqlalchemy engine setup, then the tests run fine, but I need sqlalchemy for my project.
This is is the first time I have used webtest, so not sure if I have some other conflicting config.
[Failing code] https://github.com/caffeinated-expert/frisbee/commit/ea759015de755aca1d7bffca2845b72944572bed
From the sqlaclhemy docs:
The only required key is (assuming the default prefix) sqlalchemy.url
In your test_cities_page.py file you call main with an empty dictionary, presumably to be unpacked for **settings. You need to add the appropriate setting to the dictionary you're passing to the function and it should run. : )
Related
I am trying to use the flask server, but since I faced an error, I started debugging it and by removing many codes to simplify the code and find finally reached to the following error::
Traceback (most recent call last):
File "C:\Code\SportsPersonClassifier\server\server.py", line 18, in <module>
print(classify_image())
File "C:\Code\SportsPersonClassifier\server\server.py", line 10, in classify_image
response = jsonify(util.classify_image(util.get_b64_for_virat()))
File "E:\Users\Acer\anaconda3\lib\site-packages\flask\json\__init__.py", line 358, in jsonify
if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
File "E:\Users\Acer\anaconda3\lib\site-packages\werkzeug\local.py", line 436, in __get__
obj = instance._get_current_object()
File "E:\Users\Acer\anaconda3\lib\site-packages\werkzeug\local.py", line 565, in _get_current_object
return self.__local() # type: ignore
File "E:\Users\Acer\anaconda3\lib\site-packages\flask\globals.py", line 52, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
This is my code:: in server.py
from flask import Flask, request, jsonify
import util
app = Flask(__name__)
#app.route('/classify_image', methods=['GET', 'POST'])
def classify_image():
response = jsonify(util.classify_image(util.get_b64_for_image()))
return response
if __name__ == "__main__":
print("Starting Python Flask Server For Sports Celebrity Image Classification")
util.load_saved_artifacts()
print(classify_image())
But the exact code works without any error, if I just remove jsonify() from the classify_image() function like this::
def classify_image():
response = util.classify_image(util.get_b64_for_image())
return response
If I write the classify_image function without jsonify it works as expected without error. I tried to solve the problem reading several StackOverflow answers but not working for my code. Please help me solve the problem with jsonify. Thank you.
As the error suggests, and as required by jsonify:
This requires an active request or application context
Calling the function this way via __main__ will not be within a Flask app context. Instead use app.run() to start the dev server, and then navigate to your route.
As part of my project, I've made 2 different Firestore databases. Usually, when I work with 1, it sets up fine in my project file. Now that I'm implementing BOTH of them in my python file (running discord.py), it throws up an error!
Here's the code for reference:
from firebase_admin import credentials, firestore, initialize_app
sccred = credentials.Certificate("scores-firebase.json")
scdefault_app = initialize_app(sccred)
scoredb = firestore.client(scdefault_app)
scdb = scoredb.collection('users')
stcred = credentials.Certificate("storage-firebase.json")
stdefault_app = initialize_app(stcred)
storagedb = firestore.client(stdefault_app)
stdb = storagedb.collection('january')
If I comment out the last 4 lines, it works fine, however, if I don't then the following error shows up:
Traceback (most recent call last):
File "main.py", line 51, in <module>
stdefault_app = initialize_app(stcred)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/firebase_admin/__init__.py", line 71, in initialize_app
raise ValueError((
ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.
I understood I need to add another argument, and I even went over the official firebase-admin docs for the package, yet I don't know how to add the required argument as there is no mention of it in the documentation.
Here's the documentation I referred to: https://firebase.google.com/docs/reference/admin/python/firebase_admin.db
You must specify a name for any Firebase Admin instances other than the default one:
# add the name param
stdefault_app = initialize_app(stcred, name='second_admin_instance')
Checkout the documentation for more information.
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine=create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
def main():
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
for flight in flights:
print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")
if __name__ == "__main__":
main()
Traceback (most recent call last):
File "list.py", line 6, in
engine=create_engine(os.getenv("DATABASE_URL"))
File "C:\Users\Aakash\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine__init__.py",
line 479, in create_engine
return strategy.create(*args, **kwargs)
File "C:\Users\Aakash\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\strategies.py", line 56, in create
plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'
And if change my code to:
The Problem and the traceback is in the picture.
just use this as url
"postgresql://username:password#host:port/database"
directly pass these values inside your create_engine("postgresql://username:password#host:port/database")
I was having the same problem now its gone.That worked for me. Only thing important to mention is that I got a different error altogether after creating the new user and database and moving the tables. The error was '
'' ModuleNotFoundError: No module named 'psycopg2' '''
and the solution was running: pip3 install psycopg2-binary
PS: URL details with you details.
It looks like os.getenv("DATABASE_URL") is returning None. Calling create_engine(None) give you this error. Is DATABASE_URL defined in your environment variable ?
instead of
engine=create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
type this with your url:
engine = create_engine("postgresql://scott:tiger#localhost/mydatabase")
db = scoped_session(sessionmaker(bind=engine))
To avoid typing your postgresql connection (including password) in your code define your environment variable in your terminal according this:
source ~/.bash_profile
Or you can use the short form of the command:
. ~/.bash_profile
This executes .bash_profile file in the current shell.
Additional advices concerning reloading .bash_profile can be found in the comments here.
In my case, the problem was occurring because I hadn't put the correct path of the file I was trying to upload to my AWS db.
I was having this error because of environment variable in windows.. Environment variable of database(pinot) was not properly configured. check your variable name and key both.
I am trying to use the Remote API in a local Client, following instructions given in Google documentation (https://developers.google.com/appengine/docs/python/tools/remoteapi).
I first tried from the Remote API shell, and everything is working fine. I can connect to my remote datastore and fetch data.
But when I run the following script, which is very similar to Google's example :
#!/opt/local/bin/python2.7
import sys
SDK_PATH = "/usr/local/google_appengine/"
sys.path.append(SDK_PATH)
import dev_appserver
dev_appserver.fix_sys_path()
from google.appengine.ext.remote_api import remote_api_stub
import model.account
def auth_func():
return ('myaccount', 'mypasswd')
remote_api_stub.ConfigureRemoteApi('myappid', '/_ah/remote_api', auth_func)
# Fetch some data
entries = model.account.list()
for a in entries:
print a.name
then I get an error :
Traceback (most recent call last):
File "./remote_script_test.py", line 26, in <module>
entries = model.account.list()
[...]
File "/Developer/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1333, in check_rpc_success
raise _ToDatastoreError(err)
google.appengine.api.datastore_errors.BadRequestError: Application Id (app) format is invalid: '_'
It says my application ID is a plain underscore '_', which is not the case since my app.yaml is correctly configured and when I do a
print app_identity.get_application_id()
from that script I get the correct application ID. I am under the impression that the GAE environment is not properly setup, but I could not figure out how to make it work. Does anyone have a full piece of code that works in this context ?
I am using Mac Os X Mountain Lion.
You may wish to start with remote_api_shell.py and remove stuff until it breaks, rather than add in things until it works.
For instance there's a line after the one you copied: remote_api_stub.MaybeInvokeAuthentication() is that necessary? There may be a number of necessary lines in remote_api_shell.py, maybe better to customize that rather than start from scratch.
I'm using the Windows Launcher development environment for Google App Engine.
I have downloaded Django 1.1.2 source, and un-tarrred the "django" subdirectory to live within my application directory (a peer of app.yaml)
At the top of each .py source file, I do this:
import settings
import os
os.environ["DJANGO_SETTINGS_MODULE"] = 'settings'
In my file settings.py (which lives at the root of the app directory, as well), I do this:
DEBUG = True
TEMPLATE_DIRS = ('html')
INSTALLED_APPS = ('filters')
import os
os.environ["DJANGO_SETTINGS_MODULE"] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.1')
from django.template import loader
Yes, this looks a bit like overkill, doesn't it?
I only use django.template. I don't explicitly use any other part of django.
However, intermittently I get one of two errors:
1) Django complains that DJANGO_SETTINGS_MODULE is not defined.
2) Django complains that common.html (a template I'm extending in other templates) doesn't exist.
95% of the time, these errors are not encountered, and they randomly just start happening. Once in that state, the local server seems "wedged" and re-booting it generally fixes it.
What's causing this to happen, and what can I do about it? How can I even debug it?
Here is the traceback from the error:
Traceback (most recent call last):
File "C:\code\kwbudget\edit_budget.py", line 34, in get
self.response.out.write(t.render(template.Context(values)))
File "C:\code\kwbudget\django\template\__init__.py", line 165, in render
return self.nodelist.render(context)
File "C:\code\kwbudget\django\template\__init__.py", line 784, in render
bits.append(self.render_node(node, context))
File "C:\code\kwbudget\django\template\__init__.py", line 797, in render_node
return node.render(context)
File "C:\code\kwbudget\django\template\loader_tags.py", line 71, in render
compiled_parent = self.get_parent(context)
File "C:\code\kwbudget\django\template\loader_tags.py", line 66, in get_parent
raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent
TemplateSyntaxError: Template u'common.html' cannot be extended, because it doesn't exist
And edit_budget.py starts with exactly the lines that I included up top.
All templates live in a directory named "html" in my root directory, and "html/common.html" exists. I know the template engine finds them, because I start out with "html/edit_budget.html" which extends common.html.
It looks as if the settings module somehow isn't applied (because that's what adds html to the search path for templates).
Firstly, although django is now a LOT more compatible with app engine than it once, some major incompatibilities still exist between the two platforms, meaning that you can't just dump a stock copy of django into your appengine directory and have it work out of the box. Things will error in strange ways.
There are a number of projects which aim to improve compatibility between the two projects, the most prominent is app-engine-patch. I highly suggest reading the following article http://code.google.com/appengine/articles/app-engine-patch.html and the rest of the articles located at code.google.com/appengine/articles/ under the django tab.
as for some of you're specific problems, you could try this within your setup script:
#setup django environment
from django.core.management import setup_environ
import settings
setup_envion(settings)
this is what django uses internally for setting up the environment within manage.py and is the accepted best practice for setting up django for use with scripts (like app engine).
I'm having exactly the same issue, and I haven't been able to work around it... though I've noticed it happens a LOT less with the real GAE than it does with the development server I run on my Linux workstation.