Bottle web framework: any way to run a console/shell and get it to work with Werkzeug? - bottle

I searched but couldn't find an easy way to run a console or shell akin to Django's manage.py shell or Rail's rails console
Since I just started using Bottle for an existing project, I just wanted to play around with the existing models and managers in the console. The closest I came up with was using ipdb's set_trace() and go from there, but that's not ideal by any means.
Also, I tried integrating Bottle with Werkzeug, but when I follow the instructions:
import bottle
app = bottle.Bottle()
werkzeug = bottle.ext.werkzeug.Plugin()
app.install(werkzeug)
I get the following traceback error:
Traceback (most recent call last):
File "mysite.py", line 62, in <module>
werkzeug = bottle.ext.werkzeug.Plugin()
AttributeError: 'module' object has no attribute 'werkzeug'

Try adding importing bottle.ext.werkzeug by adding this at the beginning of your source:
import bottle.ext.werkzeug

Related

Smartsheet Python SDK Copy Workspace Fails

I am trying to copy a workspace to get around the 100 object limit.
Here's my code:
def rg_copy_workspace(workspace_id, new_ws_name, api_token, debug=False):
import smartsheet
smartsheet = smartsheet.Smartsheet(api_token)
smartsheet.errors_as_exceptions(True)
new_workspace = smartsheet.Workspaces.copy_workspace(
workspace_id,
smartsheet.models.ContainerDestination({
'new_name': new_ws_name
})
)
just like the example in the Python SDK.
I am testing on a workspace with a small number of objects (I started with only one Sheet)
I'm getting an error on the folder_obj. I have tried it with and without a folder, and when I have a folder with and without contents.
rg_copy_workspace(workspace_id, new_ws_name)
Traceback (most recent call last):
File "", line 1, in
rg_copy_workspace(workspace_id, new_ws_name)
File "", line 15, in rg_copy_workspace
'new_name': new_ws_name
File "(path-deleted)\workspaces.py", line 80, in copy_workspace
folder_obj = Folder({
File "(path-deleted)\smartsheet.py", line 210, in request
"""
File "(path-deleted)\smartsheet.py", line 278, in request_with_retry
if 200 <= response.status_code <= 299:
File "(path-deleted)\smartsheet.py", line 244, in _request
native = res.native(expected)
UnexpectedRequestError: (, None)
What am I doing wrong? I don't know how the code makes it to line 80 of workspaces.py.
I updated to latest version of SDK this morning (after receiving the error)
Craig
Reputation won't let me comment.
Your code seemed to execute fine for me on the updated 1.3 SDK.
The traceback locations look to lineup with sources from roughly a year ago, but linecache is pulling from the new source to build the traceback (smartsheet.py, line 210 is actually in a comment, so it's definitely not right). I'm not sure what all the situations are that could account for this but I'd guess there are compiled bytecode (.pyc) files somewhere that are stale.
Can you share a DEBUG level log near the relevant failure so that I can see what the API request looks like?

Web2py - Auth with MongoDB

Good day,
I'm trying to use MongoDB with web2py, and for that I started with authentication, but this appeared some errors that I do not understand.
In a relational database, the web2py creates the authentication tables, MongoDB in the collections are not created automatically.
Below is the code and the error when trying to log me:
db.py
db = DAL("mongodb://localhost/primer", check_reserved=["mongodb_nonreserved",], adapter_args={"safe":False})
from gluon.tools import Auth, Service, PluginManager
auth = Auth(db)
service = Service()
plugins = PluginManager()
auth.settings.remember_me_form = False
auth.settings.actions_disabled=['register','change_password','request_reset_password','retrieve_username','profile']
auth.define_tables(username=True)
from gluon.contrib.login_methods.ldap_auth import ldap_auth
auth.settings.login_methods = [ldap_auth(server='localhost', port='10389', base_dn='ou=people,o=empresa,dc=com,dc=br')]
The authentication is by LDAP, and works perfectly in a relational database, which has the AUTH_USER table.
However, the loging using MongoDB, this appearing the following error:
Traceback (most recent call last):
File "C:\Users\Rafa\Desktop\web2py-10-06-2015p4\applications\contrato\controllers/appadmin.py", line 249, in select
nrows = db(query, ignore_common_filters=True).count()
File "C:\Users\Rafa\Desktop\web2py-10-06-2015p4\gluon\packages\dal\pydal\objects.py", line 2016, in count
return db._adapter.count(self.query,distinct)
File "C:\Users\Rafa\Desktop\web2py-10-06-2015p4\gluon\packages\dal\pydal\adapters\mongo.py", line 200, in count
count=True,snapshot=snapshot)['count'])
File "C:\Users\Rafa\Desktop\web2py-10-06-2015p4\gluon\packages\dal\pydal\adapters\mongo.py", line 319, in select
sort=mongosort_list, snapshot=snapshot).count()}
File "C:\Python27\lib\site-packages\pymongo\collection.py", line 929, in find
return Cursor(self, *args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'snapshot'
The database "primer" is created and only has two collections "posts" and "system.indexes"
Could someone help me with this error to be able to use MongoDB with the web2py?
Thank You!
Found it.
From pymongo's changelog There are a lot of breaking changes in pymongo 3.0 compared to 2.8
The following find/find_one options have been removed:
snapshot (use the new modifiers option instead)
So uninstall pymongo and try the latest before 3.0:
pip install pymongo==2.8.1
Here's my attempt:
>>> from pydal import *
No handlers could be found for logger "web2py"
>>> db = DAL('mongodb://localhost/connect_test')
>>> db.define_table('some',Field('key'),Field('value'))
<Table some (id,key,value)>
>>> db.define_table('some2',Field('ref','reference some'),Field('value'))
<Table some2 (id,ref,value)>
>>> db(db.some).select()
<Rows (1)>
>>> db(db.some).select().first()
<Row {'value': 'pir', 'key': 'bla', 'id': 26563964102769618087622556519L}>
>>>
[edit]
There's more to it. This worked at least with pydal 15.03. Googling some code i found the following in the mongo.py adapter :
from pymongo import version
if 'fake_version' in driver_args:
version = driver_args['fake_version']
if int(version.split('.')[0]) < 3:
raise Exception(
"pydal requires pymongo version >= 3.0, found '%s'"
% version)
Which was like good soil for a big frown...
After updating pydal to 15.07 it apears to brake indeed:
RuntimeError: Failure to connect, tried 5 times:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pydal\base.py", line 437, in __init__
self._adapter = ADAPTERS[self._dbname](**kwargs)
File "C:\Python27\lib\site-packages\pydal\adapters\base.py", line 57, in __call__
obj = super(AdapterMeta, cls).__call__(*args, **kwargs)
File "C:\Python27\lib\site-packages\pydal\adapters\mongo.py", line 82, in __init__
% version)
Exception: pydal requires pymongo version >= 3.0, found '2.8.1'
So it's back to upgrading pymongo :)
With pymongo at 3.0.3 and pydal at 15.07 it works like a charm again.

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. tastypie

Continuing my search for an answer to get oauth2.0 to work on pythonanywhere.
i am following this tutorial: http://ianalexandr.com/blog/building-a-true-oauth-20-api-with-django-and-tasty-pie.html
im using django 1.6 : https://www.pythonanywhere.com/wiki/VirtualEnvForNewerDjango
when i get to this line of codes:
from provider.oauth2.models import Client
# from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
User = get_user_model()
u = User.objects.get(id=1)
c = Client(user=u, name="mysite client", client_type=1, url="http://pythonx00x.pythonanywhere.com")
c.save()
c.client_id
'd63f53a7a6cceba04db5'
c.client_secret
'afe899288b9ac4127d57f2f12ac5a49d839364dc'
it seems that i got an error at line:
User = get_user_model()
and it raise an error:
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
here is the full stack trace:
Traceback (most recent call last):
File "addClient.py", line 9, in <module>
User = get_user_model()
File "/home/python2006/.virtualenvs/django16/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 136, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL)
File "/home/python2006/.virtualenvs/django16/local/lib/python2.7/site-packages/django/apps/registry.py", line 200, in get_model
self.check_models_ready()
File "/home/python2006/.virtualenvs/django16/local/lib/python2.7/site-packages/django/apps/registry.py", line 132, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
I can't seem to find out how to get the models load.
if I'm getting the idea right.
I think you may not be using the version of Django that you think you are. AppRegistryNotReady was introduced in Django 1.7. I would guess that, if you pinned your DJango version to 1.6, your code would work.

Iron Python and PyMongo Error

I'm getting this error when I try to connect to mongodb (using pymongo) with Iron Python...
Traceback (most recent call last):
File "test.py", line 3, in <module>
File "c:\Program Files (x86)\IronPython 2.7\lib\site-packages\pymongo\connecti
on.py", line 179, in __init__
File "c:\Program Files (x86)\IronPython 2.7\lib\site-packages\pymongo\mongo_cl
ient.py", line 269, in __init__
pymongo.errors.ConnectionFailure: Specified cast is not valid.
Code is pretty simple, I have replaced the db name.
import pymongo
c = pymongo.Connection('mongodb://testuser:test123#linus.mongohq.com:10021/sometestdb')
It works fine with regular python. Any ideas?
Ironpython isn't supported by pymongo - so I wouldn't advise trying to use it. You can see on the pypi page a list of supported implementations: http://pypi.python.org/pypi/pymongo
Please also see the answer here: Working with PTVS, IronPython and MongoDB
You may not be able to use pymongo with IronPython, but you can use the C#/.NET driver for MongoDB from IronPython.
Information on the driver is here. As explained in this link, you can install with nuget (PM> Install-Package mongocsharpdriver), or just download the dlls.
Once installed, you can use the assemblies in the normal way in IronPython:
# Add reference to the Mongo C# driver
import clr
clr.AddReferenceToFileAndPath("MongoDB.Bson.dll")
clr.AddReferenceToFileAndPath("MongoDB.Driver.dll")
Then use according to the MongoDB C# Driver API, for example:
# Get the MongoDB database
from MongoDB.Driver import MongoClient
client = MongoClient("mongodb://localhost")
server = client.GetServer()
database = server.GetDatabase("test")
# Get a collection
collection = database.GetCollection("users")
# Add a document
from MongoDB.Bson import BsonDocument
user = BsonDocument({'first_name':'John', 'last_name':'Smith'})
collection.Insert(user)
See the the MongoDB C# Driver API for more information.

Unable to use Diazo (plone.app.theming) on Centos

I made a webportal on my mac using plone4.1 and Diazo.
Now, I'm trying to deploy it on my server (CentOs) where there is yet another site with plone4.0.5 + collectivexdv.
When I run the site (in a brand new buildout) with my diazotheme I obtain this lines via shell (instance fg):
2011-09-27 09:32:10 ERROR plone.transformchain Unexpected error whilst trying to apply transform chain
Traceback (most recent call last):
File "/home/plone/.buildout/eggs/plone.transformchain-1.0-py2.6.egg/plone/transformchain/transformer.py", line 42, in __call__
newResult = handler.transformIterable(result, encoding)
File "/home/plone/.buildout/eggs/plone.app.theming-1.0b8-py2.6.egg/plone/app/theming/transform.py", line 205, in transformIterable
transform = self.setupTransform()
File "/home/plone/.buildout/eggs/plone.app.theming-1.0b8-py2.6.egg/plone/app/theming/transform.py", line 150, in setupTransform
xsl_params=xslParams,
File "/home/plone/.buildout/eggs/diazo-1.0rc3-py2.6.egg/diazo/compiler.py", line 106, in compile_theme
read_network=read_network,
File "/home/plone/.buildout/eggs/diazo-1.0rc3-py2.6.egg/diazo/rules.py", line 160, in process_rules
rules_doc = fixup_themes(rules_doc)
File "/home/plone/.buildout/eggs/diazo-1.0rc3-py2.6.egg/diazo/utils.py", line 49, in __call__
result = self.xslt(*args, **kw)
File "xslt.pxi", line 568, in lxml.etree.XSLT.__call__ (src/lxml/lxml.etree.c:120289)
XSLTApplyError: xsltValueOf: text copy failed
What's the matter?
I had the exact same problem and it's due an old libxml2/libxslt. Add these lines on your buildout:
[buildout]
parts =
lxml # keep lxml as the first one!
...
instance
[lxml]
recipe = z3c.recipe.staticlxml
egg = lxml
libxml2-url = ftp://xmlsoft.org/libxml2/libxml2-2.7.8.tar.gz
libxslt-url = ftp://xmlsoft.org/libxml2/libxslt-1.1.26.tar.gz
static-build = true
force = false
See Plone - XSLTApplyError: xsltValueOf: text copy failed. Probably you have an outdated libxml, as it is always the case with an old distribution like CentOS.
Use z3c.recipe.staticlxml.
It sounds like you might have overly old versions of libxml2 and/or libxslt. I encountered identical problems with libxml2 2.6.26 and libxslt 1.1.17. After upgrading to 2.7.8 and 1.2.26 (respectively) the problems went away.
If you can't upgrade the libraries locally, you can move forward quite quickly using the "z3c.recipe.staticlxml" recipe in your buildout:
[lxml]
recipe = z3c.recipe.staticlxml
egg = lxml
Just remember to delete any existing lxml egg in the eggs directory (or possibly in your ~/.buildout/eggs cache, depending on how your ~/.buildout/default.cfg it set up) first.
I just got this to work using Plone 4.2.1 on OS X 10.8 Server but only once I used the unified installer. I bumped up the libxml2 to version 2.8.0. At the time I tried this, libxml2 version 2.9.0 was broken for OS X 10.8.