Odoo - How to acess recordsets on web controller - python

I am using web controller in odoo 8 to make a REST API that will get some data and return values from the database. The problem is that I am not able to get the database from the builtin ORM.
I tried to call osv.pool.get() but gave me the error:
AttributeError: type object 'Model' has no attribute 'pool'
Odoo 8 apparently uses recordsets, but I can't use it too, and couldn't find anything usefull on docs.
How can I browse database data on web controller?
My code:
class TestWebService(http.Controller):
#http.route('/test', type='http', auth='none')
def test(self):
objects = osv.osv.pool.get("some_table")
# I need to get the objects from some_table and search them
return "Hello World"

Try Following
myobj = request.env['some.table']

Related

how to enable connectiondraining with python boto modify_lb_attribute

I have been trying to enable ELB connection draining using the modify_lb_attribute method in the python boto module; however I haven't been able to get it working. According to the documentation here http://boto.readthedocs.org/en/latest/ref/elb.html I should be able to call it like his:
modify_lb_attribute(load_balancer_name, attribute, value)
Here is an example:
modify_lb_attribute('my-elb', 'connectionDraining', 120)
When I do this however I receive the following error:
File "/Library/Python/2.7/site-packages/boto/ec2/elb/init.py", line 421, in modify_lb_attribute
value.enabled and 'true' or 'false'
AttributeError: 'NoneType' object has no attribute 'enabled'
I have been able to get it to work successfully with crossZoneLoadBalancing.
For example this works:
modify_lb_attribute('my-elb', 'crossZoneLoadBalancing', 'true')
Any help or suggestions would be appreciated.
Thanks
Working syntax for instantiating a ConnectionDrainingAttribute and passing it a to a load balancer:
from boto.ec2.elb.attributes import ConnectionDrainingAttribute
import boto.ec2.elb
connection = boto.ec2.elb.connect_to_region("region")
cda = ConnectionDrainingAttribute(connection)
cda.enabled = True
cda.timeout = 120
connection.modify_lb_attribute(
load_balancer_name='my-elb',
attribute='connectionDraining',
value=cda
)
More information about the ConnectionDrainingAttribute class can be found here in the boto docs.
When you modify the connectionDraining attribute of a load balancer, there are actually two values you can supply. The first is a boolean indicating whether you are enabling or disabling the connection draining feature. The second is an integer indicating the timeout which obviously applies only if connection draining is being enabled.
To allow you to specify both of these values, boto defines a ConnectionDrainingAttribute class in boto.ec2.elb.attributes. You must pass an instance of this class as the value to modify_elb_attribute, e.g.:
from boto.ec2.elb.attributes import ConnectionDrainingAttribute
cda = ConnectionDrainingAttribute()
cda.enabled = True
cda.timeout = 120
...
modify_lb_attribute('my-elb', cda)

web2py use of modules

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.

Getting Objects with urllib2

I have two GAE apps working in conjunction. One holds an object in a database, the other gets that object from the first app. Below I have the bit of code where the first app is asked for and gives the Critter Object. I am trying to access the first app's object via urllib2, is this really possible? I know it can be used for json but can it be used for objects?
Just for some context I am developing this as a project for a class. The students will learn how to host a GAE app by creating their critters. Then they will give me the url for their critters and my app will use the urls to collect all of their critters then put them into my app's world.
I've only recently heard about pickle, have not looked into yet, might that be a better alternative?
critter.py:
class Access(webapp2.RequestHandler):
def get(self):
creature = CritStore.all().order('-date').get()
if creature:
stats = loads(creature.stats)
return SampleCritter(stats)
else:
return SampleCritter()
map.py:
class Out(webapp2.RequestHandler):
def post(self):
url = self.request.POST['url']#from a simple html textbox
critter = urllib2.urlopen(url)
...work with critter as if it were the critter object...
Yes you can use pickle.
Here is some sample code to transfer an entity, including the key :
entity_dict = entity.to_dict() # First create a dict of the NDB entity
entity_dict['entity_ndb_key_safe'] = entity.key.urlsafe() # add the key of the entity to the dict
pickled_data = pickle.dumps(entity_dict, 1) # serialize the object
encoded_data = base64.b64encode(pickled_data) # encode it for safe transfer
As an alternative for urllib2 you can use the GAE urlfetch.fetch()
In the requesting app you can :
entity_dict = pickle.loads(base64.b64decode(encoded_data))

Unable to view item in browser based on its key in Python GAE

I'm using python GAE with webapp.
I have a form for a user to create a object in the database, something like:
class SpamRecord(db.Model):
author = db.ReferenceProperty(Author, required=True)
text = db.StringProperty()
After it's created, the user is redirected to a page whose URL contains that object's key... using code such as:
spam = SpamRecord(author=author, text=text)
spam.put()
new_spam_key = spam.key()
self.redirect("/view_spam/%s" % new_spam_key)
And this mostly works, with me being able to view items at:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQYy8oJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY_boJDA
However, there's an occasional key that won't work. Here are 2 recent examples of pages that won't load and return HTTP 404 not found errors:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-5MJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-boJDA
My html-mappings.py contains the following mapping:
(r"/view_spam/(\w+)", ViewSpamPage)
And the ViewSpamPage looks something like:
class ViewSpamPage(webapp.RequestHandler):
def get(self, spam_id):
self.response.out.write("Got here")
Can anyone offer any insight as to why this is occurring and how it may be prevented?
Thanks very much!
In regular expressions, \w doesn't match hyphens. (It will match underscores.) For that second pair of keys, this'll result in only passing part of the key to your handler.
In your URL pattern, try r"/view_spam/(.*)" instead.

How do you render the front page of a plone site in python?

The following browser view should return the content of the front page of the first Plone Site in it's context. However, I can not seem to obtain an object which is able to render html content.
from Products.Five import BrowserView
from zope.component import getMultiAdapter
class RenderFirst (BrowserView):
def __call__ (self):
def findPlones (context):
plones = context.objectValues("Plone Site")
folders = context.objectValues("Folder")
folders = set(folders).difference(set(plones))
for folder in folders:
plones += findPlones(folder)
return plones
plones = findPlones(context)
if len(plones):
default_page = plones[0].getDefaultPage()
content = plones[0].unrestrictedTraverse (default_page)
view = getMultiAdapter ((content, self.request))
return view()
else:
return "no plone"
The previous code when run tells me that the object view is not callable.
plones[0] is a Plone Site object and when called produces a KeyError for folder_listing
if I call the content object I get an AttributeError for document_view
There are lots of combinations here, of calling different adapters of different objects. Haven't yet found the right object which can render the page. Anyone know how to do this?
When I try this in a pdb a simple plones[0]() works fine.
Take a look at http://pypi.python.org/pypi/plone.subrequest.

Categories