How to get updated class variable value in Django - python

I'm having trouble getting the updated value of a class variable.
When ConnectTestAPI is called after the p_request function is executed, the class variables which are result and orderNo should updated in the post function.
Then I want to receive the updated value of class variables by looping while statement in the p_request function.
However, despite setting the values ​​of class variables with the post request, when the while statement is run, the corresponding values ​​are still empty and 0 value respectively,
So, the while statement cannot be terminated and results in a time out error.
Here is my source code. Thank you in advance!
class ConnectTestAPI(APIView):
result=""
orderNo=0
def post(self, request):
data = request.data
ConnectTestAPI.result = data['result']
ConnectTestAPI.orderNo = data['orderNo']
print(ConnectTestAPI.result) # I could successfully get data from POST request here!
print(ConnectTestAPI.orderNo) # I could successfully get data from POST request here!
return HttpResponse("ok")
def p_request():
data = {
"a" : 1234,
"b" : 5678
}
data = json.dumps(data,ensure_ascii=False).encode('utf-8')
con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
con.set("data_dict", data)
while True:
if ConnectTestAPI.result != "" and ConnectTestAPI.orderNo != 0:
break
res_result = ConnectTestAPI.result
res_orderNo = ConnectTestAPI.orderNo
return res_result, res_orderNo

You need to access the class variables using self:
class ConnectTestAPI(APIView):
result=""
orderNo=0
def post(self, request):
data = request.data
self.result = data['result']
self.orderNo = data['orderNo']
print(self.result) # I could successfully get data from POST request here!
print(self.orderNo) # I could successfully get data from POST request here!
return HttpResponse("ok")
def p_request():
data = {
"a" : 1234,
"b" : 5678
}
data = json.dumps(data,ensure_ascii=False).encode('utf-8')
con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
con.set("data_dict", data)
while True:
if self.result != "" and self.orderNo != 0:
break
res_result = self.result
res_orderNo = self.orderNo
return res_result, res_orderNo
NOTE: This usage of class attributes is not recommended. You are mutating a class attribute which has side effects on all instances of that class. In your case, an ordinary attribute initialized within __ init__() would be ok:
class ConnectTestAPI(APIView):
def __init__(self):
self.result=""
self.orderNo=0
def post(self, request):
data = request.data
self.result = data['result']
self.orderNo = data['orderNo']
print(self.result) # I could successfully get data from POST request here!
print(self.orderNo) # I could successfully get data from POST request here!
return HttpResponse("ok")
def p_request():
data = {
"a" : 1234,
"b" : 5678
}
data = json.dumps(data,ensure_ascii=False).encode('utf-8')
con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
con.set("data_dict", data)
while True:
if self.result != "" and self.orderNo != 0:
break
res_result = self.result
res_orderNo = self.orderNo
return res_result, res_orderNo

Related

Keep getting "Property object at 0x" when unpickling a class instance

I am trying to set up a multithreaded server and client, and am currently sending information wrapped in a TCP module class. I am sending the data using pickle, and have run in to a problem where attempting to access instance variables after unpickling the data leads to "Property object at 0x", instead of the instance variable.
Here is the relevant server code:
data = self.clientSocket.recv(2048)
print(data)
message = pickle.loads(data)
header = message.header
self.currUser = message.user
if header == 'user-login':
print("[recv] New login request")
self.userLogin()
client code:
username = input("Username: ")
password = input("Password: ")
message = TCPmodule().withSocket("user-login", password, self.clientSocket)
message.user = username
print(message.header)
data = pickle.dumps(message)
self.clientSocket.send(data)
Class (classmethod used and getters/setters):
def withSocket(self, header, content, socket):
self.header = header
self.content = content
self.socket = socket
self.user = ""
self.port = 0
return self
#property
def header(self):
return self._header
#header.setter
def header(self,value):
self._header = value
#property
def content(self):
return self._content
#content.setter
def content(self,content):
self._content = content
#property
def user(self):
return self._user
#user.setter
def user(self,user):
self._user = user
property object message when I print (message.header) server side
Am somewhat new to python, so I'm not sure if I'm missing something here.
Thanks

How do I use the functions within this Python script?

I have this Python script to control a PfSense router via FauxAPI. The problem is that when i call a function it gives an error. I think i'm calling the function wrong. Does anyone know how to call them?
Here is a link to the API i'm using: https://github.com/ndejong/pfsense_fauxapi
I have tried calling config_get(self, section=none) but that does not seem to work.
import os
import json
import base64
import urllib
import requests
import datetime
import hashlib
class PfsenseFauxapiException(Exception):
pass
class PfsenseFauxapi:
host = '172.16.1.1'
proto = None
debug = None
version = None
apikey = 'key'
apisecret = 'secret'
use_verified_https = None
def __init__(self, host, apikey, apisecret, use_verified_https=False, debug=False):
self.proto = 'https'
self.base_url = 'fauxapi/v1'
self.version = __version__
self.host = host
self.apikey = apikey
self.apisecret = apisecret
self.use_verified_https = use_verified_https
self.debug = debug
if self.use_verified_https is False:
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
def config_get(self, section=None):
config = self._api_request('GET', 'config_get')
if section is None:
return config['data']['config']
elif section in config['data']['config']:
return config['data']['config'][section]
raise PfsenseFauxapiException('Unable to complete config_get request, section is unknown', section)
def config_set(self, config, section=None):
if section is None:
config_new = config
else:
config_new = self.config_get(section=None)
config_new[section] = config
return self._api_request('POST', 'config_set', data=config_new)
def config_patch(self, config):
return self._api_request('POST', 'config_patch', data=config)
def config_reload(self):
return self._api_request('GET', 'config_reload')
def config_backup(self):
return self._api_request('GET', 'config_backup')
def config_backup_list(self):
return self._api_request('GET', 'config_backup_list')
def config_restore(self, config_file):
return self._api_request('GET', 'config_restore', params={'config_file': config_file})
def send_event(self, command):
return self._api_request('POST', 'send_event', data=[command])
def system_reboot(self):
return self._api_request('GET', 'system_reboot')
def system_stats(self):
return self._api_request('GET', 'system_stats')
def interface_stats(self, interface):
return self._api_request('GET', 'interface_stats', params={'interface': interface})
def gateway_status(self):
return self._api_request('GET', 'gateway_status')
def rule_get(self, rule_number=None):
return self._api_request('GET', 'rule_get', params={'rule_number': rule_number})
def alias_update_urltables(self, table=None):
if table is not None:
return self._api_request('GET', 'alias_update_urltables', params={'table': table})
return self._api_request('GET', 'alias_update_urltables')
def function_call(self, data):
return self._api_request('POST', 'function_call', data=data)
def system_info(self):
return self._api_request('GET', 'system_info')
def _api_request(self, method, action, params=None, data=None):
if params is None:
params = {}
if self.debug:
params['__debug'] = 'true'
url = '{proto}://{host}/{base_url}/?action={action}&{params}'.format(
proto=self.proto, host=self.host, base_url=self.base_url, action=action, params=urllib.parse.urlencode(params))
if method.upper() == 'GET':
res = requests.get(
url,
headers={'fauxapi-auth': self._generate_auth()},
verify=self.use_verified_https
)
elif method.upper() == 'POST':
res = requests.post(
url,
headers={'fauxapi-auth': self._generate_auth()},
verify=self.use_verified_https,
data=json.dumps(data)
)
else:
raise PfsenseFauxapiException('Request method not supported!', method)
if res.status_code == 404:
raise PfsenseFauxapiException('Unable to find FauxAPI on target host, is it installed?')
elif res.status_code != 200:
raise PfsenseFauxapiException('Unable to complete {}() request'.format(action), json.loads(res.text))
return self._json_parse(res.text)
def _generate_auth(self):
# auth = apikey:timestamp:nonce:HASH(apisecret:timestamp:nonce)
nonce = base64.b64encode(os.urandom(40)).decode('utf-8').replace('=', '').replace('/', '').replace('+', '')[0:8]
timestamp = datetime.datetime.utcnow().strftime('%Y%m%dZ%H%M%S')
hash = hashlib.sha256('{}{}{}'.format(self.apisecret, timestamp, nonce).encode('utf-8')).hexdigest()
return '{}:{}:{}:{}'.format(self.apikey, timestamp, nonce, hash)
def _json_parse(self, data):
try:
return json.loads(data)
except json.JSONDecodeError:
pass
raise PfsenseFauxapiException('Unable to parse response data!', data)
Without having tested the above script myself, I can conclude that yes you are calling the function wrong. The above script is rather a class that must be instantiated before any function inside can be used.
For example you could first create an object with:
pfsense = PfsenseFauxapi(host='<host>', apikey='<API key>', apisecret='<API secret>')
replacing <host>, <API key> and <API secret> with the required values
Then call the function with:
pfsense.config_get() # self is not passed
where config_get can be replaced with any function
Also note
As soon as you call pfsense = PfsenseFauxapi(...), all the code in
the __init__ function is also run as it is the constructor (which
is used to initialize all the attributes of the class).
When a function has a parameter which is parameter=something, that something is the default value when nothing is passed for that parameter. Hence why use_verified_https, debug and section do not need to be passed (unless you want to change them of course)
Here is some more information on classes if you need.
You need to create an object of the class in order to call the functions of the class. For example
x = PfsenseFauxapi() (the init method is called during contructing the object)
and then go by x.'any function'. Maybe name the variable not x for a good naming quality.

Disablling cache in Django 1.8

I am having a weird bug that seems related to Djangos caching.
I have a 3-step registration process:
insert personal data
insert company data
summary view and submit all data for registration
If person A walks through the process to the summary part but does not submit the form and
person B does the same, person B gets the data of person A in the summary view.
The data gets stored in a Storage object which carries the data through each step. Every new registration instanciates a new Storage object (at least it should).
While debugging I've found that Django does not call any method in the corresponding views when the cache is already warmed up (by another running registration) and I guess that's why there is no new Storage instance. Hence the cross-polution of data.
Now I'm perfectly aware that I can decorate the method with #never_cache() (which it already was) but that doesn't do the trick.
I've also found that the #never_cache decorator does not work properly prior to Django 1.9(?) as it misses some headers.
One solution that I've found was to set these headers myself with #cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True). But that also doesn't work.
So how can I properly disable caching for these methods?
Here is some relevant code:
# views.py
def _request_storage(request, **kwargs):
try:
return getattr(request, '_registration_storage')
except AttributeError:
from .storage import Storage
storage = Storage(request, 'registration')
setattr(request, '_registration_storage', storage)
return storage
...
# Route that gets called by clicking the "register" button
#secure_required
#cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True)
# also does not work with #never_cache()
def registration_start(request, **kwargs):
storage = _request_storage(request)
storage.clear()
storage.store_data('is_authenticated', request.user.is_authenticated())
storage.store_data('user_pk', request.user.pk if request.user.is_authenticated() else None)
return HttpResponseRedirect(reverse_i18n('registration_package', kwargs={'pk': 6}))
def registration_package(request, pk=None, **kwargs):
"""stores the package_pk in storage"""
...
def registration_personal(request, pk=None, **kwargs):
from .forms import PersonalForm
storage = _request_storage(request)
if request.method == 'POST':
form = PersonalForm(request.POST)
if form.is_valid():
storage.store_form('personal_form_data', form)
return HttpResponseRedirect(reverse_i18n('registration_company'))
else:
if request.GET.get('revalidate', False):
form = storage.retrieve_form('personal_form_data', PersonalForm)
else:
form = storage.retrieve_initial_form('personal_form_data', PersonalForm)
return render_to_response('registration/personal.html', {
'form': form,
'step': 'personal',
'previous': _previous_steps(request),
}, context_instance=RequestContext(request))
# the other steps are pretty much the same
# storage.py
class Storage(object):
def __init__(self, request, prefix):
self.request = request
self.prefix = prefix
def _debug(self):
from pprint import pprint
self._init_storage()
pprint(self.request.session[self.prefix])
def exists(self):
return self.prefix in self.request.session
def has(self, key):
if self.prefix in self.request.session:
return key in self.request.session[self.prefix]
return False
def _init_storage(self,):
if not self.prefix in self.request.session:
self.request.session[self.prefix] = {}
self.request.session.modified = True
def clear(self):
self.request.session[self.prefix] = {}
self.request.session.modified = True
def store_data(self, key, data):
self._init_storage()
self.request.session[self.prefix][key] = data
self.request.session.modified = True
def update_data(self, key, data):
self._init_storage()
if key in self.request.session[self.prefix]:
self.request.session[self.prefix][key].update(data)
self.request.session.modified = True
else:
self.store_data(key, data)
def retrieve_data(self, key, fallback=None):
self._init_storage()
return self.request.session[self.prefix].get(key, fallback)
def store_form(self, key, form):
self.store_data(key, form.data)
def retrieve_form_data(self, key):
return self.retrieve_data(key)
def retrieve_form(self, key, form_class):
data = self.retrieve_form_data(key)
form = form_class(data=data)
return form
def retrieve_initial_form(self, key, form_class):
data = self.retrieve_form_data(key)
form = form_class(initial=self.convert_form_data_to_initial(data))
return form
def convert_form_data_to_initial(self, data):
result = {}
if data is None:
return result
for key in data:
try:
values = data.getlist(key)
if len(values) > 1:
result[key] = values
else:
result[key] = data.get(key)
except AttributeError:
result[key] = data.get(key)
return result
def retrieve_process_form(self, key, form_class, initial=None):
if request.method == 'POST':
return form_class(data=request.POST)
else:
data = self.get_form_data(key)
initial = self.convert_form_data_to_initial(data) or initial
return form_class(initial=initial)
I've tested this across browser, computers and networks. When I clear the cache manually it works again.
(Easy to see with just debugging print() statements which do not get called with a warm cache.)
It can't be too hard to selectively disable caching, right?
Additional question:
Could it be that the #never_cache() decorator just prevents browser-caching and has nothing to do with the Redis cache?

Return JSON from a Python Class to Another Class

How would I return the same exact JSON data from one class to another?
Code:
class Class1(webapp.RequestHandler):
def get(self):
random_id = str(uuid.uuid1())
time_now = int(time.time())
info = {
id: random_id,
now: time_now
}
json_info = json.dumps(info)
print json_info
self.response.write(info)
class Class2(webapp.RequestHandler):
def get(self):
getting_info = self.Class1()
getting_info_time = getting_info['now']
print getting_info_time
Error:
class1_info = self.Class1()
AttributeError: 'Class2' object has no attribute 'Class1'
Edit (more details):
One part of my application needs the whole JSON output while the other part needs just the now value from the info dictionary. And both classes would be using the same exact data from the info dictionary.
I've been trying to get the now output but I just get error messages.
Attempt:
Note: using #Alex's answer (with #snakecharmerb recommendation of memcache)
Code:
from google.appengine.api import memcache
class Class1(webapp.RequestHandler):
def generate_data(self):
random_id = str(uuid.uuid1())
time_now = int(time.time()))
id_cached = memcache.add(key=random_id, value=random_id, time=600)
get_id_cached = memcache.get(key=random_id, value=random_id, time=600)
time_cached = memcache.add(key=time_now, value=time_now, time=600)
get_time_cached = memcache(key=time_now)
info = {
id: get_id_cached,
now: get_time_cached
}
json_info = json.dumps(info)
return json_info
def get(self):
self.response.write(generate_data())
class Class2(webapp.RequestHandler):
def get(self):
getting_info = Class1().generate_data()
print getting_info
Result:
{"id": "9d752605-a20d-11e7-8bfd-bfe81b332704", "time": "1506356501"}
{"id": "9b95e899-a20d-11e7-b137-bfe81b332704", "time": "1506356498"}
It would help to know more about what you're trying to do, but based on your code snippet, this should do it.
Class1(webapp.RequestHandler):
#staticmethod
def perform():
random_id = str(uuid.uuid1())
time_now = int(time.time()))
info = {
id: random_id,
now: time_now
}
json_info = json.dumps(info)
print json_info
return json_info
def get(self):
self.response.write(self.perform())
Class2(webapp.RequestHandler):
def get(self):
getting_info = Class1.perform()
getting_info_time = getting_info['now']
print getting_info_time
Another route would be having Class2 inherit Class1, another route would be moving the 'perform' function outside at the file level. It's hard to give a more appropriate answer without more context.
Edit:
Creating a 'BaseHandler' that both classes inherit seems more appropriate then. Check for existence of the cached ID, if None, create & add.
RANDOM_ID = "RANDOM_ID"
MyBaseHandler(webapp.RequestHandler):
#staticmethod
def get_random_id():
cached = memcache.get(key=RANDOM_ID)
if not cached:
cached = {id: str(uuid.uuid1()), now: int(time.time()))}
memcache.add(key=RANDOM_ID, value=cached, time=600)
return cached
Class1(MyBaseHandler):
def get(self):
self.response.write(self.get_random_id())
Class2(MyBaseHandler):
def get(self):
print self.get_random_id()['now']
If both handlers need to access the same data, delegate the data generation to a function.
def generate_data():
random_id = str(uuid.uuid1())
time_now = int(time.time()))
info = {
id: random_id,
now: time_now
}
return info
Class1(webapp.RequestHandler):
def get(self):
info = generate_data()
json_info = json.dumps(info)
print json_info
self.response.write(info)
Class2(webapp.RequestHandler):
def get(self):
info = generate_data()
getting_info_time = info['now']
print getting_info_time
This approach will work if the data is newly generated for each request. If you need to return the same data for each request then you need to store it for example in the datastore, memcache or a session so that it can be retrieved.

Using NumPy for discrete networking request event simulator?

I need to simulate the requests and responses being processed by a network of routers and began small by creating a server class:
class NBServer:
"""Name based content server"""
def __init__(self, _id):
self.id = _id
self.requests = deque('x')
self.responses = deque('x')
self.req_load = 0
self.res_load = 0
self.color = ''
self.forwarding_table = {}
self.content_store = {}
self.pending_table = {}
def __str__(self):
return 'current load: ' + str(req_load + req_load)
def request(self, content_name, requester_id):
self.requests.append((content_name, requester_ids))
self.req_load += 1
def response(self, content_name, content_url):
self.responses.append((content_url, destination_ids))
return ((content_url, destination_ids))
def process(self):
for req in self.requests:
# Case 1: content in cache
if content_name in self.content_store:
return self.content_name[content_name]
# Case 2: duplicate request exists
elif content_name in self.pending_table:
self.pending_table[content_name].append(requester_id)
# Case 3: add to PT, forward to next router
else:
self.pending_table[content_name] = [requester_id]
response = response.popleft()
if response:
for dest_id in self.pending_table[content_name]:
nodes[dest_id].response(content_name, content_url)
del self.pending_table[content_name]
However, now I am getting confused on how the communication between the routers can be represented:
Any advice on how to do this with NumPy?
Any help is greatly appreciated!

Categories

Resources