Using named group to call function in view django - django

I don't know if something like this is possbile but I would like to call a function based on the named group value in the urls.py config.
This is what I have been looking at
url.py snippet
url(r'^ajax/ValidateLogin/(?P<funcname>\w{13})/$', Validate),
views.py snippet
def checkUsername(request):
user = User.objects.get(username=request.POST.get('username',''))
if user == None:
response = simplejson.dumps({'success':'True','validate':'True'})
else:
response = simplejson.dumps({'success':'True','validate':'False'})
return HttpResponse(response,content_type='application/javascript; charset=utf-8')
def Validate(request,funcname):
return funcname(request)
This just returns that unicode object isn't callable which I understand but how do I then convert it to call the view function check username? An example of url that should call this is ajax/ValidateLogin/checkUsername
Thanks

remote_function_calls = {
'check_username' : check_username,
}
def Validate(request, funcname):
try:
return remote_function_calls[funcname](request)
except KeyError:
response = http.HttpResponse("Invalid function")
response.status_code = 403
return response
Another method to define which functions are valid
def valid_function(request):
return http.HttpResponse("This function may be called remotely")
valid_function.remote_call_valid = True
def erase_everything_function(request):
world.delete()
valid_functions = dict([(k, v) for k, v in globals().iteritems() if
getattr(v, 'remote_call_valid', None) == True])

Use this:
def Validate(request,funcname):
return locals()[funcname](request)
Although this kind of thing is a bit of a security risk since any user can call any arbitrary function available to python by passing the right "funcname".

Related

Django redirect by calling function view?

I need to redirect while keeping the original request. Is this approach inline with Django 3 logic or am I creating some furute catastrofe?
def final_view(request):
# use some_new_variable to do stuff and then display it in the template
return render(request, another_template_name, {})
def original_view(request):
# do stuff
request.some_new_variable = "x"
return final_view(request)
Not sure exactly what you're trying to accomplish, but you could always pass "some_new_variable" via the URL
For instance:
views.py
def original_view(request):
x = # do your stuff here
return redirect('final_view_url', var=x)
def final_view(request, var)
final_var = # do some additional stuff with var here
return render(request, another_template_name)
urls.py
path('/final_view/<var>', views.final_view, name="final_view_url")
So you send your original request to "original_view", do some stuff, then pass that variable into the URL to "final_view"

Custom admin form error "need more than 1 value to unpack"

I have been adapting this article How to Add Custom Action Buttons to Django Admin to my particular circumstance and things are working pretty well except for this one strange error I am getting. In my forms.py I have defined class DenyForm: (Note the request parameter in form_action is not the usual API request. I have a model class Request.) What should form_action be returning?
class DenyForm(ApproveOrDenyForm):
def form_action(self, request, admin_approver ):
print "forms DenyForm Called."
justification = self.cleaned_data['justification']
request.admin_deny(admin_approver=admin_approver,justification=justification)
return [request]
#return request.admin_deny(admin_approver=admin_approver,justification=justification)
This results in a message of
“‘Please correct the errors below.’ need more than 1 value to unpack”.
I have tried different endings to my form_action method. If my last line is:
return request
I get “‘Please correct the errors below.’ ‘Request’ object is not iterable”.
If the last line is:
return request.admin_deny(admin_approver=admin_approver,justification=justification)
I get this … “‘Please correct the errors below.’ ‘NoneType’ object is not iterable”. That is because admin_deny() does not return anything. What should form_action be returning?
Update: Here is the code that call form_action():
class ApproveOrDenyForm(forms.Form):
justification = forms.CharField(
required=True,
widget=forms.Textarea,
)
def save(self, req, login ):
try:
user = User.objects.filter(login=login).get()
req, action = self.form_action(req, user )
except Exception as e:
error_message = str(e)
self.add_error(None, error_message)
raise
return req, action
When you call form_action you are expecting it to return an iterable of two items - req and action. So you need to ensure that form_action() returns a list or tuple of exactly those two things.
It is not clear to me from the post you linked to, or your code, what the action returned is supposed to be - maybe just a result of the action performed. You need to check that to decide whether your action method needs to return something else.
Something like this should work:
def form_action(self, request, admin_approver ):
justification = self.cleaned_data['justification']
action = request.admin_deny(admin_approver=admin_approver, justification=justification)
# action will be None if admin_deny does not return anything,
# but the code calling this function expects it, so return it anyway.
return (request, action)

json serialisation of dates on flask restful

I have the following resource:
class Image(Resource):
def get(self, db_name, col_name, image_id):
col = mongo_client[db_name][col_name]
image = col.find_one({'_id':ObjectId(image_id)})
try:
image['_id'] = str(image['_id'])
except TypeError:
return {'image': 'notFound'}
return {'image':image}
linked to a certain endpoint.
However, image contains certain datetime objects inside. I could wrap this around with `json.dumps(..., default=str), but I see that there is a way of enforcing this on flask-restful. It's just not clear to me what exactly needs to be done.
In particular, I read:
It is possible to configure how the default Flask-RESTful JSON
representation will format JSON by providing a RESTFUL_JSON
attribute on the application configuration.
This setting is a dictionary with keys that
correspond to the keyword arguments of json.dumps().
class MyConfig(object):
RESTFUL_JSON = {'separators': (', ', ': '),
'indent': 2,
'cls': MyCustomEncoder}
But it's not clear to me where exactly this needs to be placed. Tried a few things and it didn't work.
EDIT:
I finally solved with this:
Right after
api = Api(app)
I added:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
#return int(obj.strftime('%s'))
return str(obj)
elif isinstance(obj, datetime.date):
#return int(obj.strftime('%s'))
return str(obj)
return json.JSONEncoder.default(self, obj)
def custom_json_output(data, code, headers=None):
dumped = json.dumps(data, cls=CustomEncoder)
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
api = Api(app)
api.representations.update({
'application/json': custom_json_output
})
Just cleared this out, you just have to do the following:
app = Flask(__name__)
api = Api(app)
app.config['RESTFUL_JSON'] = {'cls':MyCustomEncoder}
This works both for plain Flask and Flask-RESTful.
NOTES:
1) Apparently the following part of the documentation is not that clear:
It is possible to configure how the default Flask-RESTful JSON
representation will format JSON by providing a RESTFUL_JSON attribute
on the application configuration. This setting is a dictionary with
keys that correspond to the keyword arguments of json.dumps().
class MyConfig(object):
RESTFUL_JSON = {'separators': (', ', ': '),
'indent': 2,
'cls': MyCustomEncoder}
2)Apart from the 'cls' argument you can actually overwrite any keyword argument of the json.dumps function.
Having created a Flask app, e.g. like so:
root_app = Flask(__name__)
place MyConfig in some module e.g. config.py and then configure root_app like:
root_app.config.from_object('config.MyConfig')

can we return variable from the python decoretor?

I have used function for checking session key in django (it need to code).
def sessioncheck(unikey):
from django.contrib.sessions.models import Session
try:
session_obj = Session.objects.get(pk=unikey)
userinfo = session_obj.get_decoded()
# Here i want some data to return
userkey = userinfo["session_datakey"]
username = userinfo["session_user"]
return userkey,username # i need it in my function and as many other stuff to with it
except(ObjectDoesNotExist, KeyError):
response = JsonResponse({"expire": "u r not here anymore"})
return response
Here I like to use it as decorator? but not getting it how can be done i.e return part for the userkey
The above function i like to use as decorector.
# Currunt i m using as
def sessioncall(request, unikey):
gotukey,username = sessioncheck(unikey)
if type(token).__name__ is not "JsonResponse":
# Lots of work using **gotukey** and **username** over here
# work change from function to function for use gotukey
response = JsonResponse({"hmm": "man you are in now"})
return response
else:
return gotukey
I know we can use decorator to raise error but i also want to return some values if it success.
my question is can we write decorator? or we need to use at function call only for return

Django: method call in django models

I have a model like this
class User(model):
username = XXX
addr1 = xxx
def get_username(self):
return self.username + 'some message'
def get_addr1(self):
return self.addr1 + 'some string'
and code I want to iterate through each objects and if function with get_+field.name exists then call that method, otherwise return the field itself.
Is there a way to do this? Below is pseudo code:
for field in each_obj._fields.itervalues():
if get_+fieldname exists then:
return that function call
else:
return self.field.name
you can call hasattr(obj, 'get_'+fieldname) to know if the method is there but the best to do that is to actually override __getattr__ in your class and just let Python do the rest.
Take a look at how I fake python attributes here http://ilian.i-n-i.org/faking-attributes-in-python-classes/ and also check for the alternative solution in the comments.
for var in obj.__dict__:
try:
print getattr(obj, 'get_%s' %var)()
except(AttributeError):
print var