flask redirect from closure - redirect

def check_login(func):
"""Check if user is logged in."""
def decorator(*args, **kwargs):
if not login_session_test():
print ("Not logged in - redirect to /login")
flash ("Well that was wrong. Chicken winner. No more dinner.")
return redirect(url_for('login'))
print ("Logged in, do what needs to be done.")
return func(*args, **kwargs)
return decorator
#check_login
#app.route("/sacred/secret/stuff", methods=['GET'])
def funfunfun():
return "Super fun"
It never redirects to /login but gives some garbage like page.
Swapping the #/closure order yields:
AssertionError: View function mapping is overwriting an existing endpoint function: decorator
I am not yet fully pythonized.

Your decorator order is incorrect, and you are not copying across the function name to the wrapper function.
Use this order:
#app.route("/sacred/secret/stuff", methods=['GET'])
#check_login
def funfunfun():
return "Super fun"
Otherwise the undecorated function is registered for the view.
Use #functools.wraps() to have various pieces of metadata copied over from the original wrapped function to the wrapper that replaces it:
from functools import wraps
def check_login(func):
"""Check if user is logged in."""
#wraps(func)
def decorator(*args, **kwargs):
if not login_session_test():
print ("Not logged in - redirect to /login")
flash ("Well that was wrong. Chicken winner. No more dinner.")
return redirect(url_for('login'))
print ("Logged in, do what needs to be done.")
return func(*args, **kwargs)
return decorator
Routes need an endpoint name, and if you don't specify one explicitly, Flask uses the name of the function (from functionobj.__name__). But your decorator wrapper object has the name decorator, so if you use the decorator more than once Flask complains that it already has used that endpoint name.
#functools.wraps() copies across the __name__ attribute, so now your decorator wrapper is also called funfunfun, whereas another decorated route function gets to keep its name too.

Related

Graphene: How to add a function before query execute?

Is there a way to execute a function before all query?
When I add an annotation above Query class, It makes an error
AssertionError: Type <function Query at 0x104d1dd30> is not a valid ObjectType.
def my_func(f):
#wraps(f)
def my_func_wrap(*args, **kwargs):
//do something
return f(*args, **kwargs)
return my_func_wrap
#my_func
class Query(graphene.ObjectType):
node = relay.Node.Field()
users = graphene.List(lambda: UserSchema)
def resolve_users(self, info):
//do something
return User.query.all()
schema = graphene.Schema(query=Query)
If i add the annotation to every resolver, It works fine.
but I will add more than 20 resolvers and I don't think adding the annotation to every resolver is good idea.
Yes, you can. Just create a custom View class inheriting from GraphQLView and override dispatch method then use your own view class as graphql endpoint handler. Something like this:
class CustomGraphQLView(GraphQLView):
def dispatch(self, request, *args, **kwargs):
// do something
super(CustomGraphqlView, self).dispatch(request, *args, **kwargs)
If you want to manipulate the queryset itself, I suggest to use graphene-django-extras and override the list_resolver method on its query fields(DjangoFilterListField, DjangoFilterPaginateListField, ...) class and use your own custom class.
You can call super on override methods or copy the exact code from their source and edit them.

In WTForms, how do I make optionally required field if another one is empty?

I have two fields where user can choose one to enter but they can't enter both and they can't skip both either. Requiered() makes it that they can't skip one and Optional() let them skip both.
I can only find an example for when you want another to be mandatory when you fill one field but I don't know how to modify it to my case because the example inherits a Required() validator which makes the two fields both required.
Following is the example I found here. Does anybody know if there's a native way to do what I described now or know how to modify this to suit my case?
class RequiredIf(Required):
# a validator which makes a field required if
# another field is set and has a truthy value
def __init__(self, other_field_name, *args, **kwargs):
self.other_field_name = other_field_name
super(RequiredIf, self).__init__(*args, **kwargs)
def __call__(self, form, field):
other_field = form._fields.get(self.other_field_name)
if other_field is None:
raise Exception('no field named "%s" in form' % self.other_field_name)
if bool(other_field.data):
super(RequiredIf, self).__call__(form, field)

plone.formwidget - Is it possible to set a MasterSelect Field as an AutocompleteFieldWidget?

I am trying to set a MasterSelect field to an AutocompleteFieldWidget.
I'm using AutocompleteFieldWidget from plone.formwidget.autocomplete and the MasterSelectField from plone.formwidget.MasterSelect. The slave field belonging to the MasterSelectField is also a MasterSelectField.
The autocomplete functions as it should (retrieving the values based on input), but the slave field's choices do not change. However, when its not set as an autocomplete, everything works as it should.
Edit:
In my buildout-cache, I looked at widget.py in plone.formwidget.masterselect and tried placing a print statement in getSlaves and that function wasn't getting called. I tried the render function and that wasn't getting called either. Then I placed a print statement in MasterSelectField and that was notgetting called. Setting the field to an Autocomplete widget removes any trace that its a Master Select field.
Edit: In the init.py file in plone.formwidget.masterselect, I placed a print statement in the init function of the MasterSelectField, and the slave widget does print, where as in getSlaves in widget.py it doesn't. This is the output I'm getting from printing in the init and what I should be getting in getSlaves:
({'action': 'vocabulary', 'masterID': 'form-widgets-IMyForm-master_field',
'control_param': 'master_value', 'name': 'IMyForm.slave_field',
'vocab_method': <class 'my.product.vocabulary.SlaveVocab'>},)
I have my interface:
from plone.directives import form
class IMyForm(model.Schema):
form.widget(master_field=AutocompleteFieldWidget)
master_field = MasterSelectField(
title=_(u'Master'),
slave_fields=({'name':'IMyForm.slave_field',
'action':'vocabulary',
'source':MySource,
'control_param':'master_value'
}),
required=True,
)
slave_field = MasterSelectField(title=_(u'Slave Field'),
source=SlaveVocab,
slave_fields=(....
)
required=False,
)
I have my source object for the master field:
class MySource(object):
implements(IQuerySource)
def __init__(self, context):
simple_terms = []
#Query portal catalog for unique indexes, and fill with simple terms
self.vocab = SimpleVocabulary(simple_terms)
def __contains__(self, term):
return self.vocab.__contains__(term)
def getTermByToken(self, token):
return self.getTermByToken(token)
def getTerm(self, value):
return self.getTerm(value)
def search(self, query_string):
return [term for term in self.vocab if query_string in term.title.lower()]
class MySourceBinder(object):
implements(IContextSourceBinder)
def __call__(self, context):
return MySource(context)
My slave field's source is:
class SlaveVocab(object):
grok.implements(IContextSourceBinder)
def __init__(self, **kw):
self.master_value = kw.get('master_value', None)
def __call__(self, context):
if self.master_value is None or self.master_value == "--NOVALUE--"
self.master_value = getattr(context,'master_field',None)
#Still nothing, return empty vocabulary
if self.master_value is None or self.master_value == '--NOVALUE--':
return SimpleVocabulary([])
terms = []
#If not null, building a simple vocabulary to return
return SimpleVocabulary(terms)
I did a print statement in call of the Slave Vocabulary and it was being called, but nothing was being passed in.
I also tried using another widget, ChosenFieldWidget. I get the same results in that it functions as it should, but the slave field's choices do not change. Is it possible to set a master select field to an autocomplete? If so, what am I doing wrong?
Also, I'm using Solgema.fullcalendar and the content type extends the IEventBasic behavior, so I don't have access to using my own form class I would've liked to have used since Solgema seems to render its own forms.
Edit:
I am using Plone 4.3

Tastypie Urls and Filters

I would like to use tastypie with some slightly different urls. I would like them to be like this:
/api/v1/city/London/make_default
/api/v1/city/Paris/make_default
/api/v1/city/Singapore/remove_city
Where the city itself can be any city in the city table in my db and the resource name is the method I want to perform. Each method has it's own resource. In tastypie the urls seem to give me some trouble with this. The prepend_urls that I have keep giving me a 301 redirect.
class CityResource(Resource):
class Meta
def make_default(self, request, city_name):
return super(ViewTemplateResource, self).get_object_list(request)\
.filter(name=city_name, client=request.user).update(default=True)
def prepend_urls(self):
return [
url(r"^city/(?P<city_id>[\w\d_.-]+)/(?P<resource_name>%s)/$" % self._meta.resource_name,
self.wrap_view('make_default')),
]
So to solve this I did it a bit differently:
first the wrap view was avoiding the normal pathway of tastypie instead of adding to it:
def dispatch_default(self, request, city_name, **kwargs):
self.queryset = City.objects.filter(name=city_name, client=user)
return self.dispatch('detail', request, **kwargs) # could use super here too instead of copying the normal code
def prepend_urls(self):
return [
url(r"^city/(.+)/(?P<resource_name>%s)$" % self._meta.resource_name,
self.wrap_view('dispatch_detail')),
]

Scala: Generate a block that conditionally runs another block

In the Circumflex framework, you can map an URL to a block like this:
get("/foo") = {
"hello, world!"
}
which, when browsing to /foo, will show the given string as expected. Now, to write a complete web application, you almost always need some form of authentication and authorisation. I'm trying to write some kind of wrapper for the above construct, so I can write this:
get("/foo") = requireLogin {
"hello, world!"
}
The requireLogin method would then check if the user is logged in, and if yes, execute the given block. If not, however, it should do a redirect to the login page.
Now I somehow can't get the syntax right (i'm still a Scala newbie). How would you do this in a generic fashion?
Try something like this:
def executeMaybe[A](work: => A): Option[A] =
if (util.Random.nextBoolean)
Some(work)
else
None
This executes the passed code with probability 0.5, returning Some(<result delivered by work>), or returns None is the other cases. You can call it either like this:
val v = executeMaybe(42)
or with block notation:
val v = executeMaybe {
// do some work
// provide return value
}
The trick is to use a by-name parameter, signalled by the => symbol. Read more e.g. here: http://daily-scala.blogspot.com/2009/12/by-name-parameter-to-function.html
The way I asked it, Jean-Philippe's answer is correct.
But here's some information specific to Circumflex:
In the Circumflex RequestRouter, the following can be used to implement the required method:
def requireLogin (f: => RouteResponse ): RouteResponse = {
if(loggedIn) {
return f
}
else {
return sendRedirect("/login")
}
}
The reason behind this was getting clear with the hint from Jean-Philippe's answer, and once I remembered that the following call isn't an assignment of a block to some internal data, but is mapped to another method call instead.
So, the call
get("/") = {...}
is actually mapped to this:
get.update("/", {...})
The block is passed in as a By-Name parameter, so the return value of requireLogin must be the same - which, for Circumflex, is RouteResponse, and not a function.
You also can use j2ee container authentication with <login-config> and <security-constraint> stuff inside web.xml