I'm using werkzeug in a Django project using Apache/mod_wsgi. What I want to do is access the werkzeug python shell without there actually being an error. The only way I can figure to do this is to intentionally cause an error when the url pattern url(r'^admin/shell', forceAnError()) is matched.
Admittedly, intentionally causing an error isn't the optimal course of action, so if there's a way to simply call/import/render/access the werkzeug python shell from a template or something, that would be the better solution.
If you wrap your WSGI application in a werkzeug.debug.DebuggedApplication with evalex on, you'll get a shell available at /console:
from werkzeug.wrappers import Request, Response
from werkzeug.debug import DebuggedApplication
#Request.application
def app(request):
return Response("Normal application, nothing to see here...")
app = DebuggedApplication(app, evalex=True)
# console_path is another optional keyword argument.
# you can guess what it does.
Related
I have a Flask project where the entry point is application.py and then I have several other modules like, e.g. variant.py, etc.
The project structure is:
>my_app_dir/
application.py
views/
__init__.py
users.py
variant.py
...
For variant.py, it's a function like:
import ...
from views import *
def variant(variant_id, subset='all', language='en'):
...
if subset == 'all':
return json.dumps(x)
return json.dumps([{subset: y[subset]} for y in x])
The point is I want to use variant.py like an API, so I am testing via iPython, something like, but it's returning an error:
from views import variant as v
aa = v.variant('22-38212762-A-G')
...
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.
I've tried googling but couldn't find any similar case, yet I experimented several things for no avail.
In the end, I found out a way to get what I was looking for:
from views import application, autocomplete
from views.variant import variant
ctx = application.test_request_context(path='/login',method='POST', data={'user':'demo','password':'demo123'})
ctx.push()
variant('22-38212762-A-G')[:50]
autocomplete.autocomplete('ttll','gene').json
So, essentially, the trick bit is:
ctx = application.test_request_context(path='/login',method='POST', data={'user':'demo','password':'demo123'})
ctx.push()
I am using Django 1.6.2 in virtualenv, Ubuntu 12.04 LTS. As I wanted to shift my project to https, I installed django-sslserver. The project needs self signing, and works fine for Home Page. However, apps in my django project encounter problems. Not all pages are redirected to https, and hence causes 404 error (works only if explicitly prefixed as https). Also, the overall template (appearance i.e. static files?) is lost.
What exactly is happening here? How to make sure that all pages are redirected to https and works the same way as in http?
Edited: My pull request has been merged. Static resources are served normally now.
The problem is that the runsslserver command is not implemented to serve static resources. A way to fix is to override get_handler in PATH_TO_PYTHON_SITE_PACKAGE/sslserver/management/commands/runsslserver.py like so:
# ...
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django import get_version
# ...
class Command(runserver.Command):
# ...
help = "Run a Django development server over HTTPS"
def get_handler(self, *args, **options):
"""
Returns the static files serving handler wrapping the default handler,
if static files should be served. Otherwise just returns the default
handler.
"""
handler = super(Command, self).get_handler(*args, **options)
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', False)
if use_static_handler:
return StaticFilesHandler(handler)
return handler
# ...
You might want to get your site package path with
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
I've also submitted a pull request in case you want to branch, merge, and reinstall it as a package on your own.
Cheers
I have a python function in modules in web2py to send e-mails.It has the following code
message = response.render('scheduler/connectionmessage.html',cont)
I get the error
<type 'exceptions.NameError'> name 'response' is not defined"
How can I make render available in modules? The objective is to have a few such scripts under modules and execute them via scheduler from a stub under controllers.
More code -
def send_email_invites():
from gluon import *
from gluon.template import render
db = current.db
......<execute query and populate dictionary>
message = response.render('scheduler/connectionmessage.html',cont)
That is about it.
Your code already includes from gluon import *, which means you have imported the thread local current object. That object includes the response object for the current request, so you should refer to current.response rather than just response.
Note, this is not necessary in model, controller, and view files because those files are executed in a global environment that already includes the response object (along with much of the rest of the web2py API).
For more details, see http://web2py.com/books/default/chapter/29/04/the-core#Accessing-the-API-from-Python-modules.
Try this before calling response.render()
from gluon.globals import Response
response = Response()
And I know it's tempting, but try to avoid from xyz import * and be explicit.
I have following code written in python in order to communicate with ExistDB using eulexistdb module.
from eulexistdb import db
class TryExist:
def __init__(self):
self.db = db.ExistDB(server_url="http://localhost:8899/exist")
def get_data(self, query):
result = list()
qresult = self.db.executeQuery(query)
hits = self.db.getHits(qresult)
for i in range(hits):
result.append(str(self.db.retrieve(qresult, i)))
return result
query = '''
let $x:= doc("/db/sample/books.xml")
return $x/bookstore/book/author/text()
'''
a = TryExist()
response = a.get_data(query)
print response
I am amazed that this code runs fine in Aptana Studio 3 giving me the output I want, but when running from other IDE or using command "python.exe myfile.py" brings following error:
django.core.exceptions.ImproperlyConfigured: Requested setting EXISTDB_TIMEOUT, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I used my own localsetting.py to solve the problem using following code:
import os
# must be set before importing anything from django
os.environ['DJANGO_SETTINGS_MODULE'] = 'localsettings'
... writing link for existdb here...
Then I get error as:
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
How do I configure the setting in Django to suit for ExistDB? Help me here please..
Never Mind. I found the answer with little research from this site. What I did was created a localsetting.py file with following configurations.
EXISTDB_SERVER_USER = 'user'
EXISTDB_SERVER_PASSWORD = 'admin'
EXISTDB_SERVER_URL = "http://localhost:8899/exist"
EXISTDB_ROOT_COLLECTION = "/db"
and in my main file myfile.py I used :
from localsettings import EXISTDB_SERVER_URL
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'localsettings.py'
and In the class TryExist I changed in __ init __() as:
def __init__(self):
self.db = db.ExistDB(server_url=EXISTDB_SERVER_URL)
PS: Using only os.environ['DJANGO_SETTINGS_MODULE'] = 'localsettings' brings the django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty..
The reason your code works in an IDE but not at the command line is probably that you have a difference in what Python environments are used to run your code.
I've done a couple of tests:
Virtualenv with eulexistdb installed but not Django. eulexistdb tries to load django.conf but fails and so does not try to get its configuration from a Django configuration. Ultimately, your code runs without error.
Virtualenv with 'eulexistdb*and* Django:eulexistdbtries to loaddjango.conf` and succeed. I then tries to get is configuration from the Django configuration but fails. I get the same error you describe in your question.
To prevent the error in the presence of a Django installation, the problem can be fixed by adding a Django configuration like you did in your accepted self-answer. But if the code you are writing does not otherwise use Django, that's a bit of a roundabout way to get your code to run. The most direct way to fix the problem is to simply add a timeout parameter to the code that creates the ExistDB instance:
self.db = db.ExistDB(
server_url="http://localhost:8080/exist", timeout=None)
If you do this, then there won't be any error. Setting the timeout to None leaves the default behavior in place but prevents eulexistdb from looking for a Django configuration.
My python GAE app's central application file looks like this:
import webapp2
import homepage
import user_auth
import user_confirm
import admin_user
import admin_config
import config
app = webapp2.WSGIApplication([
(user_auth.get_login_url(), user_auth.LoginHandler),
(user_auth.get_logout_url(), user_auth.LogoutHandler),
("/user/confirm", user_confirm.UserConfirmHandler),
("/admin/config", admin_config.AdminConfigHandler),
("/admin/user/add", admin_user.AdminAddUserHandler),
("/admin/user", admin_user.AdminUserHandler),
("/", homepage.HomepageHandler),
], debug=True)
As you can see, I must import a bunch of request handlers, but for each request, only one of them is used, the other imports are just useless!
That's a big waste of memory and performance because those unnecessary imports also import other things on their own. Does Google App Engine have some "caching" mechanism or something that makes these unnecessary imports negligible? I think not.
How can I avoid them? I just haven't found out the way to import 1 Request Handler per request. If I put all the routing to app.yaml, that would work the way I want, but it makes things complex because I must write app = webapp2.WSGIApplication(... for every request handler file and repeat those boring urls twice (both in the python file and in app.yaml).
Found the way here, already built into webapp2
http://webapp-improved.appspot.com/guide/routing.html#lazy-handlers