Update: We have recently improved the @anvil.server.http_endpoint
decorator to do most of these things for you! Check out the reference docs here.
In particular, you can now accomplish the same as @david.wylie’s code with:
@anvil.server.http_endpoint("/dave", enable_cors=True)
def dave_handler(**kwargs):
rnd = randint(1, 100000)
app_tables.log.add_row(data="New "+str(rnd))
return "Dave called successfully : " + str(rnd)
We have also added a feature which solves @jshaffstall’s problem, which is that endpoints execute in a separate session from the rest of the app, if they are invoked from outside your app. This is to prevent a nasty set of attacks called XSRF (Cross-Site Request Forgery), where a malicious outsider can cause a logged-in user to make changes to their account that they weren’t really expecting to make!
You can now selectively disable these protections for a particular endpoint, like this:
@anvil.server.http_endpoint("/user/logout", cross_site_session=True)
def logout_api(**qs):
anvil.users.logout()
This will cause your Python code to execute in the same session as the rest of your app, which means that the anvil.users.logout()
call will log the user out.
Note that doing this carries significant security risks - it means that this endpoint may be triggered by malicious sites! (In this case, it means random malicious websites can log your users out. Probably not too bad in this case, but you can imagine what kind of trouble an unprotected /delete-my-account
endpoint might invite!)
We’ve written a bit more about the security issues in the HTTP endpoint reference docs, but for a full treatment there are many excellent resources that you should read carefully. The web is full of pitfalls, which Anvil tries hard to protect you from – remove the safety catch at your peril