passing strftime() into Google app engine and jinja2 - python

I have a Google App Engine Python script trying to pass the variable "time" as a strftime() call. I have jinja2 set up to read the html file with {{time}} in it as that variables destination
class MainPage(BlogHandler):
time = ''
def get_time(you):
return strftime('%U %A',gmtime())
def get(self):
time = self.get_time
self.render('front.html',time = time)
When I render/write out the whole thing into a simple div tag I get an object memory locator rendered in html
<bound method MainPage.get_time of <main.MainPage object at 0x1030f0610>>
obviously its not processing this out as a string. Am I using the wrong time function, is this a GAE issue? is this a Jinja2 issue? Is this a python issue? I'm clearly not sure how to follow up and resolve this. Thanks or any good critical advice.
All I want is to render a formattable time function to a string so i can use it in GAE scripts.

All you have to do is call the get_time() method:
time = self.get_time()
By not calling the method, all you do is store a reference to the method, and Jinja2 then takes the str() result of that method to include it in your template output:
>>> from time import strftime, gmtime
>>> class MainPage():
... def get_time(self):
... return strftime('%U %A',gmtime())
...
>>> mp = MainPage()
>>> mp.get_time
<bound method MainPage.get_time of <__main__.MainPage instance at 0x1031c7320>>
>>> mp.get_time()
'07 Saturday'

Related

no value for argument self in unbound method call

Thanks for reading this. I've spent the past 48 hours trying to get this code to work. First of all I must disclose that this is for a college assignment. I'm not looking for any assistance or comment on how I might 'gain' in the assignment, I just need to figure out what I'm doing wrong. I have googled the issue and I've read through tutorials on classes and I do feel like I understand them and have got the examples to work. This one issue is stumping me.
So, I have a class which will read a database as follows:
import mysql.connector
import pandas as pd
class DAOdv:
#dbConn=mysql.connector.connect()
def __init__(self):
# import the config file
config=pd.read_csv('./files/config.ini')
dbName=config.iloc[int(config[config['item']=='databaseName'].index[0])]['setting']
uname=config.iloc[int(config[config['item']=='username'].index[0])]['setting']
hst=config.iloc[int(config[config['item']=='host'].index[0])]['setting']
prt=config.iloc[int(config[config['item']=='port'].index[0])]['setting']
# create the connection
self.dbConn=mysql.connector.connect(
host=hst,
database=dbName,
port=prt,
username=uname,
password='' # no password on Server as yet
)
def allClients(self):
cursor=self.dbConn.cursor()
sSQL = 'SELECT * FROM clients'
cursor.execute(sSQL)
results=cursor.fetchall()
return results
daoDV=DAOdv()
and the 'server' code which is:
from flask import Flask
from daoDV import DAOdv
app=Flask(__name__, static_url_path='',static_folder='')
# curl "http://127.0.0.1:5000/clients"
#app.route('/clients')
def getAll():
results=DAOdv.allClients()
return results
In python, the second last line above, DAOdv is underlined in red and hovering over it produces the message "no value for argument self in unbound method call"
What am I doing wrong? I'm assuming the error is in the class?? but I can't figure out what.
Many thanks for your help with this.
Seamus
DAOdv is the class itself, not the instantiated object which you create at the end with: daoDV=DAOdv().
Change your server code to:
from daoDV import daoDV # note the capitalization - we're importing the object here
#(...)
results = daoDV.allClients()
Your method allClients() is an instance method, not a class method.
That's why you should call it like:
results=DAOdv().allClients()
Methods can be an instance or class method.
Class methods are methods which have #classmethod decorator.

"str object is not callable"

I'm trying to make it so the api will lookup the item code that has been inputted by the user. Everytime I run this code it allows the user to input an item code but rather than process that code into the api it says:
"str object is not callable" with reference to line 14 which is result=api.item_lookup('')
The code below works when you remove api.item_lookup=raw_input() and manually put the item code in api.item_lookup, eg: result=api.item_lookup('B017WMMAVU').
from flask import Flask
from flask import render_template
from flask_bootstrap import Bootstrap
app = Flask("charity_third_page")
from amazonproduct import API
from lxml import etree
from lxml import objectify
api=API(locale='uk')
api.item_lookup = raw_input()
result=api.item_lookup('')
for item in result.Items.Item:
print '%s' % (item.ItemAttributes.Title)
item=api.item_lookup('', ResponseGroup='OfferSummary')
print str(item.Items.Item.OfferSummary.LowestNewPrice.getchildren()[0]/ 100.0)
Any help on how to get this to run would be much appreciated.
Because:
api.item_lookup = raw_input()
Is assigning a string (the result of raw_input) to api.item_lookup. Then you're trying to call it as a method. Maybe:
myStr = raw_input()
result = api.item_lookup(myStr)
instead.
You assigned the results of raw_input, a string, to api.item_lookup. A string is not callable, but on the next line you try to call the method api.item_lookup. Perhaps you meant to pass the input to the function, rather than overwriting it.
result = api.item_lookup(raw_input())

Flask redirect to url and pass query strings

I have a view that is defined like such:
#views.route('/issues')
def show_view():
action = request.args.get('action')
method = getattr(process_routes, action)
return method(request.args)
in my process_routes module, I would like to call this method, and pass query string values. I have the following code:
return redirect(url_for('views.show_view', action='create_or_update_success'))
I have a function in process_routes named create_or_update_success
I am getting
BuildError: ('views.show_view', {'action': 'create_or_update_success'}, None)
views is a blueprint. I can successfully call
/issues?action=create_or_update_success
In my browser.
What am I doing wrong?
The first part, views., has to reflect the first argument you give to your Blueprint() object exactly.
Don't be tempted to set that first argument to __name__, as that is likely to contain the full path of the module when inside a package. In your case I suspect that to be some_package.views rather than just views.
Use a string literal for the Blueprint() first argument instead:
views_blueprint = Blueprint('views', __name__)
so you can refer to url_for('views.show_view') without getting build errors.

Passing a variable to a JSON web service

I am accessing the class from the code api_service.py, which can be found here. When I call the first function, I have no problem, because no variables are passed:
from api_service import ApiService
import json
def main():
api_key = *removed*
access_token = *removed*
calling = ApiService(api_key,access_token)
survey_list = calling.get_survey_list()
But when I use the same type of routine as above to call a function from ApiService that requires a variable, I'm told that I should pass an object.
survey_details = calling.get_survey_details("1234")
survey_details = json.loads(json.dumps(survey_details))
print survey_details
The specific error message:
{u'status': 3, u'errmsg': u"Value '1234' for field '_data' is not of type object"}
Details for the get_survey_details aspect of the SurveyMonkey API are here, although I think a python-guru can solve this without knowing about the API.
This is a javascript/json object:
{field:'value'}
You have passed a string which, doesn't count as an "object" for these purposes.
Note that the error message is being generated by the service you are accessing. This question would be better directed to the creator of the service.

Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine

I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way:
#from data.models import Program
import basehandler
class ProgramViewHandler(basehandler.BaseHandler):
def get(self,slug):
# query = Program.all()
# query.filter('slug =', fslug)
self.render_template('../presentation/program.html',{})
Whenever this code gets executed I get this error on the stacktrace:
appengine\ext\webapp__init__.py", line 511, in call
handler.get(*groups)
TypeError: get() takes exactly 2 arguments (1 given)
I have done some debugging, but this kind of debugging exceeds my level of debugging. When I remove the slug from def get(self,slug) everything runs fine.
This is the basehandler:
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class BaseHandler(webapp.RequestHandler):
def __init__(self,**kw):
webapp.RequestHandler.__init__(BaseHandler, **kw)
def render_template(self, template_file, data=None, **kw):
path = os.path.join(os.path.dirname(__file__), template_file)
self.response.out.write(template.render(path, data))
If somebody could point me in the right direction it would be great! Thank you! It's the first time for me to use stackoverflow to post a question, normally I only read it to fix the problems I have.
You are getting this error because ProgramViewHandler.get() is being called without the slug parameter.
Most likely, you need to fix the URL mappings in your main.py file. Your URL mapping should probably look something like this:
application = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)])
The parenthesis indicate a regular expression grouping. These matched groups are passed to your handler as arguments. So in the above example, everything in the URL following the initial "/" will be passed to ProgramViewHandler.get()'s slug parameter.
Learn more about URL mappings in webapp here.
If you do this:
obj = MyClass()
obj.foo(3)
The foo method on MyClass is called with two arguments:
def foo(self, number)
The object on which it is called is passed as the first parameter.
Maybe you are calling get() statically (i.e. doing ProgramViewHandler.get() instead of myViewHandlerVariable.get()), or you are missing a parameter.

Categories

Resources