How do I use a global variable in cherrypy? - python

I need to access a global variable that keeps its state over diffferent server requsts.
In this example the global variable is r and it is incremented at each request.
How can I make r global in cherrypy?
import cherrypy
import urllib
class Root(object):
#cherrypy.expose
def index(self, **params):
jsondict = [('foo', '1'), ('fo', '2')]
p = urllib.urlencode(jsondict)
if r!=1
r=r+1
raise cherrypy.HTTPRedirect("/index?" + p)
return "hi"
cherrypy.config.update({
'server.socketPort': 8080
})
cherrypy.quickstart(Root())
if __name__ == '__main__':
r=1

To access a global variable, you have to use the global keyword followed by the name of the variable. However, if r is going to be used only in the Root class, I recommend you to declare it as a class variable:
class Root(object):
r = 1
#cherrypy.expose
def index(self, **params):
#...
if Root.r != 1:
Root.r += 1
#...

I had the same problem. It was solved after realizing my program could access the member variables of an imported library.
First, make a file called myglobals.py and put this in it
r=0
visitors = 0
Then in your server:
import myglobals
class Root(object):
#cherrypy.expose
def index(self, **params):
#...
if myglobals.r != 1:
myglobals.r += 1
#...

Related

Python | check if dict{} item is in list[]

Attempting to check an in-memory list, plant_list[] against a JSON payload from an api.
If the incoming payload's dict name matches inside of plant_list the if should fire off.
Instead my script only returns null
Please point out my mistakes.
The JSON sent over the api call is:
{ "name":"swizz", "days": "7", "price": 2.00 }
Source Code
from flask import Flask, request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
#app.route('/', methods=['GET', 'POST'])
def home():
return 'Tiny'
plant_list = []
class Plant(Resource):
def get(self, name):
return {'Name':name}, 200
def post(self, name):
payload = request.get_json()
for x in range(0, len(plant_list)):
if payload['name'] == plant_list[x]['name']:
return {'message': f'''Item {payload['name']} already stored in database.'''}
else:
plant_list.append(payload)
return plant_list, 201
api.add_resource(Plant, '/plant/<string:name>')
if __name__ == '__main__':
app.run(port=9004, debug=True)
You can test for key in dict simply by: if key_name in my_dict:... So, if "price" in plant_list[x]:
You are setting plant_list as a global. If you want to use that inside a Class, you should define it inside the function in your class:
plant_list = []
class Plant(Resource):
....
def post(self, name):
global plant_list
....
Not sure why you need it as a global variable. Perhaps you want:
class Plant(Resource):
plant_list = []
....
def post(self, name):
....

How to pass a variable from a function to a class?

How can I print path outside function:
class FirstClas:
path = ''
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(path)
This method don't print anything.
This result:
C:\Python\python.exe C:/Users/JOHN/Desktop/test/tt.py
Process finished with exit code 0
You need to create an instance from the class that you created.
I would suggest doing this:
test = FirstClas()
print(test.num())
Hope this helps
Your method never gets called, and the class variable path is pointless here. Do:
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(FirstClas().num()) # note that this is outside the class!
I don't think you quite understand the purpose of classes, but here's how to make what you have "work" (in the sense that there are no fatal errors):
File global_variable.py
def init_global_variable():
"""initialize variable"""
global GLOBALS_DICT
GLOBALS_DICT = {}
def set_variable(name, value):
"""set variable"""
try:
GLOBALS_DICT[name] = value
return True
except KeyError:
return False
def get_variable(name):
"""get variable"""
try:
return GLOBALS_DICT[name]
except KeyError:
return "Not Found"
init_global_variable() # ADDED.
File tt.py
import os
#import lib.global_variable as glv
import global_variable as glv # Since I don't have your whole package.
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
def imag(self):
icon_file = os.path.join(
glv.get_variable("APP_PATH"),
glv.get_variable("DATA_DIR"),
"paths",
"PathExcel",
)
return icon_file
class Second:
# Put statements in a method so they don't run when the class is defined.
def run(self):
test = FirstClas()
print('first: ' + test.num())
print('second: ' + test.imag())
second = Second()
second.run()
Output:
first: C:\Users\JOHN\Desktop\test.txt
second: Not Found\Not Found\paths\PathExcel
the path does not changed(path = ' ') because you don't run the function num

NameError: name 'convert_symbol_to_int' is not defined

I've got an error: NameError: name 'convert_symbol_to_int' is not defined when I run this code:
class ReadData():
def __init__(self, sheet_path):
self.book = xlrd.open_workbook(sheet_path)
self.sheet = self.book.sheet_by_index(1)
self.users = []
def read(self):
for row_index in range(2, self.sheet.nrows):
rows = self.sheet.row_values(row_index)
if rows[1] != '' and rows[2] != '' and rows[4] != '':
woman = convert_symbol_to_int(row[8])
man = convert_symbol_to_int(row[9])
def convert_symbol_to_int(self,arg):
if arg == '○':
return 2
elif arg == '×':
return 1
elif arg == '△':
return 0
else:
return -1
x = ReadData('./data/excel1.xlsx')
x.read()
I really cannot understand why this error happens.
Why can't I access convert_symbol_to_int? How should I fix this?
you should use
man = self.convert_symbol_to_int(row[9])
Exactly as Kalyan Reddy already answered, you have to call the method with self, which is a pointer to the class itself. The following example shows the difference between externally declared functions and methods defined within the class:
def hello():
print("hello, world!")
class Greeting(object):
def __init__(self, world):
self.world = world
def hello(self):
print("hello, {}!".format(self.world))
def make_greeting(self):
hello() # this will call the function we created outside the class
self.hello() # this will call the method defined in the class
The purpose of self has already been explained in this question:
What is the purpose of self?

Return list function python

I am new to python and I'm trying this code below q Objects1 return to list
how can I do this?
it returns me the following error
File "/ home/paulo/Desktop/testepy2/objectMIB.py", line 53
     return
SyntaxError: 'return' outside function
thank you
from pysnmp.entity import engine, config
from pysnmp import debug
from pysnmp.entity.rfc3413 import cmdrsp, context, ntforg
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.smi import builder
import threading
import collections
import time
MibObject = collections.namedtuple('MibObject', ['mibName',
'objectType', 'valueFunc'])
class Mib(object):
"""Stores the data we want to serve.
"""
def __init__(self):
self._lock = threading.RLock()
self._test_count = 0
self._test_get = 10
self._test_set = 0
def getTestDescription(self):
return "My Description"
def getTestCount(self):
with self._lock:
return self._test_count
def setTestCount(self, value):
with self._lock:
self._test_count = value
def getTestGet(self):
return self._test_get
def getTestSet(self):
return self._test_set
def setTestSet(self):
self._test_set = value
class ListObejtc ():
mib = objectMIB.Mib()
objects1 = [MibObject('MY-MIB', 'testDescription', mib.getTestDescription),
MibObject('MY-MIB', 'testCount', mib.getTestCount),MibObject('MY-MIB', 'testGet', mib.getTestGet), MibObject('MY-MIB', 'testSet', mib.getTestSet) ]
print objects1
return
It's normal for the code you have shown nested inside "ListObejtc" to be in a method, like so:
class ListObejtc ():
def __init__(self):
pass
def doObjects(self):
mib = objectMIB.Mib()
objects1 = [MibObject('MY-MIB', 'testDescription', mib.getTestDescription),
MibObject('MY-MIB', 'testCount', mib.getTestCount),MibObject('MY-MIB', 'testGet', mib.getTestGet), MibObject('MY-MIB', 'testSet', mib.getTestSet) ]
print objects1
return objects1
You got a SyntaxError because the return as you had it was in class context, and it makes no sense there.

self.response.out.write() - how to use it properly?

I have a class that doesn't extend webapp.RequestHandler, and I can't use self.response.out.write(), I get:
AttributeError: Fetcher instance has no attribute 'response'
If I extend webapp.RequestHandler (I thought it would work), I get:
AttributeError: 'Fetcher' object has no attribute 'response'
How can I use that method properly? Sometimes print doesn't work either; I just get a blank screen.
EDIT:
app.yaml:
application: fbapp-lotsofquotes
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: main.py
source (the problematic line is marked with #<- HERE):
import random
import os
from google.appengine.api import users, memcache
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app
import facebook
class Quote(db.Model):
author = db.StringProperty()
string = db.StringProperty()
categories = db.StringListProperty()
#rating = db.RatingProperty()
class Fetcher(webapp.RequestHandler):
'''
Memcache keys: all_quotes
'''
def is_cached(self, key):
self.fetched = memcache.get(key)
if self.fetched:
print 'ok'#return True
else:
print 'not ok'#return False
#TODO: Use filters!
def fetch_quotes(self):
quotes = memcache.get('all_quotes')
if not quotes:
#Fetch and cache it, since it's not in the memcache.
quotes = Quote.all()
memcache.set('all_quotes',quotes,3600)
return quotes
def fetch_quote_by_id(self, id):
self.response.out.write(id) #<---------- HERE
class MainHandler(webapp.RequestHandler):
def get(self):
quotes = Fetcher().fetch_quotes()
template_data = {'quotes':quotes}
template_path = 'many.html'
self.response.out.write(template.render(template_path, template_data))
class ViewQuoteHandler(webapp.RequestHandler):
def get(self, obj):
self.response.out.write('viewing quote<br/>\n')
if obj == 'all':
quotes = Fetcher().fetch_quotes()
self.render('view_many.html',quotes=quotes)
else:
quotes = Fetcher().fetch_quote_by_id(obj)
'''for quote in quotes:
print quote.author
print quote.'''
def render(self, type, **kwargs):
if type == 'single':
template_values = {'quote':kwargs['quote']}
template_path = 'single_quote.html'
elif type == 'many':
print 'many'
self.response.out.write(template.render(template_path, template_values))
'''
CREATORS
'''
class NewQuoteHandler(webapp.RequestHandler):
def get(self, action):
if action == 'compose':
self.composer()
elif action == 'do':
print 'hi'
def composer(self):
template_path = 'quote_composer.html'
template_values = ''
self.response.out.write(template.render(template_path,template_values))
def post(self, action):
author = self.request.get('quote_author')
string = self.request.get('quote_string')
print author, string
if not author or not string:
print 'REDIRECT'
quote = Quote()
quote.author = author
quote.string = string
quote.categories = []
quote.put()
def main():
application = webapp.WSGIApplication([('/', MainHandler),
(r'/view/quote/(.*)',ViewQuoteHandler),
(r'/new/quote/(.*)',NewQuoteHandler) ],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
You're not routing to Fetcher when you initialize a WSGIApplication. Rather, you create an instance manually in other handlers. Thus, App Engine will not initialize your request and response properties. You can manually do so in from the handlers you route to, such as MainHandler and ViewQuoteHandler. E.g.:
fetcher = Fetcher()
fetcher.initialize(self.request, self.response)
quotes = fetcher.fetch_quotes()
Note that fetcher really doesn't have to be a RequestHandler. It could be a separate class or function. Once you have request and response objects, you can pass them around as you choose.

Categories