I have a little question about request attribute in my function located in a python file (not my view):
def my_function(model, request):
instance = model.objects.filter(application=request.cur_app, display=True).order_by('order')
return instance
In this same file, I call my function like this:
for element in my_function(my_model):
... do something ...
But I get this issue:
my_function() missing 1 required positional argument: 'request'
I don't understand How I can solve this issue, because if I add 'request' in my loop, I get:
name 'request' is not defined
Thank you !
Update:
I have a middleware.py file which contains this:
class MultiSiteMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.cur_app = WebApplication.objects.get_current(request)
return self.get_response(request)
And this is this middleware that I want to get in my menu.py file in this function:
def list_of_edition():
""" Return list of editions
:return queryset
"""
instance = NavbarMenuSettings.objects.filter(application=MultiSiteMiddleware, display=True).order_by('order')
return instance
When you run this function
my_function
you must given two params model and request
model = ...
request = ...
my_function(model,request)
django function base view 1st positional argument is request,
def funtionbaseview(request, arg1, arg2)
Related
It's an example that's as similar as possible, and it's not exactly the same as the actual code.
But I believe it's easy to understand.
class Fruits:
...
def get_sample_data(self, df):
...
data = {
'put_file_attachment': >here<,
}
...
class DataInputForm(forms.Form):
attachment = forms.FileField()
class MyView(FormView):
template_name = 'view.html'
form_class = DataInputForm
def get_success_url(self):
return str(
reverse_lazy("milk")
)
def post(self, request, *args, **kwargs):
get_file = request.FILES.get('attachment')
...
k = Fruits()
k.load_data()
return self.render_to_response(context)
I would like to bring the attachment(In fact, get_file) that the user attached to the web class Fruits's >here<
In other words, I would like to save the file(get_file) in DB column (put_file_attachment) by the user's attachment. How can I get a value passed to a request from another class to another class?
I tried to get 'get_file' by creating a MyView object in the Fruit class, but it doesn't work.
Is that possible in this structure or Am I not understanding the concept of request??
The variable must be explicitly passed to the class for it to be available. It's currently in a different scope, so it won't be available.
So, either refactor your Fruits class to take your file as an argument to your constructor (ie, __init__), or pass it in some other way, such as a parameter to your load_data method.
I have created a class based AWS lambda function in python called requestHandler.py as below
from action_dispatcher import ActionDispatcher
class RequestHandler(ActionDispatcher):
#staticmethod
def createTemplate(event, context):
return "Hello world"
My action_dispatcher.py is as shown below.
import json
class ActionDispatcher(object):
def __call__(self, event, context, *args, **kwargs):
action = event.get('action')
handler = getattr(self, action, None)
if handler is None:
return json.loads({'status': 'error', 'code': 404, 'message':"Action {0} not found.".format(action) })
return handler(request, *args, **kwargs)
With this above setup and lambda handler as requestHandler.RequestHandler, i get error "RequestHandler() takes no arguments" in this case i create action as createTemplate. so i want to call this method from RequestHandler.
It looks to me like you are trying to call your class instead of an instance of the class. RequestHandler() will call the __init__ method to initialize an instance of the class. Since you haven't defined the method it doesn't take any arguments. To access __call__ you need to call an instance of your class.
handler = RequestHandler()
result = handler(request, context, *args, **kwargs)
You can only define a handler in python using def handler(event, context):. However, I found a package that allows you to call the handler as a class
Usage, as noted in their documentation, is as follows:
pip install aws-lambda-handler
import aws_lambda
class EchoHandler(aws_lambda.Handler):
"""Echo handler."""
def perform(self, request, **k):
"""Echo perform method."""
response = aws_lambda.Response()
response.body = self.request.event
return response
echo_handler = EchoHandler()
# `echo_handler` is now a callable function you can map your AWS Lambda function to
The solution for my problem was simple, as mentioned by jacinator, i should try with class instance.
earlier for lambda handler, i used pass class as handler, now i am passing the instance of the class as handler.
Added the line in requestHandler.py rhandler = RequestHandler()
So previously my lambda handler was like requestHandler.RequestHandler, now it has been changed to requestHandler.rhandler.
i'm trying to use arguments on django but when middleware is working on the views.py function, it returns me this error: call() got an unexpected keyword argument 'id'.
views.py function
from django.http import HttpResponse
from .middleware import SampleMiddleware
#SampleMiddleware
def myfunc(request, id):
return HttpResponse(id)
This is my middleware
class SampleMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
This is the URL
path('myfunc/<id>', views.myfunc, name='myfunc'),
A middleware class isn't a decorator. In order to use it as one you'd have to wrap it with the decorator_from_middleware utility.
here is my view.py
class categAdmin(admin.ModelAdmin):
change_form_template = 'category_forms.html'
list_display = ['title']
model = Category
fields = ['status','title','category_post','body', 'photo',
'url','slider','Gallery','lists','pk_tree','video','maps']
# def render_change_form(self, request, context, **kwargs):
# post = Post.objects.all()
# context['eve'] = post
# return super(categAdmin,self).render_change_form(request, context, **kwargs)
def item_add(request, self, post_id):
tree = post_id
return self.add_view(request, extra_context={'tree': tree})
i am getting error item_add() missing 1 required positional argument: 'request'
You need to swap self and request parameters.
def item_add(self, request, post_id):
tree = post_id
...
Always remember that methods are bound to objects and whenever you call methods, python implicitly passes the self argument(the object on which the method is being called) to the method call, In your example:
class CategAdmin:
def item_add(self, request, post_id):
pass
would be the signature format, note that the self object is the first parameter in the method signature. So when you do
categoryAdmin = CategAdmin()
categoryAdmin.item_add(request,123)
this is what will be called by the python interpreter CategAdmin.item_add(categoryAdmin,request,123)
One more feedback would be to improve your coding style, i.e follow some conventions like always start class names with Capital letter, give meaningful names to class and methods and variables.
This makes your code more readable and via this debugging will be way faster.
Cheers!
How can I elegantly bind some arbitrary value and flask route? Suppose, I want to access this value in my session interface implementation or in before_request hook.
Now I'm doing it in such way:
#app.route('/foo/<bar>', defaults={'_my_val': True}):
def foo(bar, _my_val): # this is ugly hack
pass
And access this value through request object like this:
class MyRequest(flask.Request):
def get_my_val(self):
return (self.url_rule.defaults or {}).get('_my_val', False)
But it looks like a hack.
UPD: Looks like it can be done by extending werkzeug.routing.Rule class and adding **kwargs to its constructor. Is it ok to override Rule class in flask?
Eventually I ended up overriding flask's Request and Rule classes:
# here app is a Flask current application object
from flask import Request as FlaskRequest
from werkzeug.routing import Rule as FlaskRule
class Request(FlaskRequest):
def is_foo(self):
return bool(self.url_rule._foo) if self.url_rule else False
def get_bar(self):
return getattr(self.url_rule, '_bar')
class Rule(FlaskRule):
def __init__(self, *args, **kwargs):
for param in ('_foo', '_bar'):
setattr(self, param, kwargs.pop(param, None))
super().__init__(*args, **kwargs)
# app initialization
app.request_class = Request
app.url_rule_class = Rule
# route example
#app.route('/path', _foo=True, _bar='baz')
def route():
pass