Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a python flask function which is call by a post request?

In below code, your_method is called when your_command is executed in slack

from flask_slack import Slack
slack = Slack(app)
app.add_url_rule('/', view_func=slack.dispatch)
@slack.command('your_command', token='your_token',
           team_id='your_team_id', methods=['POST'])
def your_method(**kwargs):
 text = kwargs.get('text')
 return text

How to call this your_method from another function in this python program.

Eg.

def print:
 a = your_method('hello','world')

This gives me error =>

Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
return func(**kwargs)
File "sample.py", line 197
a = your_method('hello','world')
TypeError: your_method() takes exactly 0 arguments (1 given)
like image 998
Vikas Saini Avatar asked Feb 03 '26 21:02

Vikas Saini


2 Answers

Based on the signature, tis function only accepts keyword arguments.

def your_method(**kwargs):

You call it with positional arguments.

your_method('hello', 'world')

You either need to change the signature

def your_method(*args, **kwargs)

or call it differently

your_method(something='hello', something_else='world')
like image 175
dirn Avatar answered Feb 06 '26 11:02

dirn


You cannot do this. Methods decorated with the route decorator cannot accept arguments passed in by you. View function arguments are reserved for route parameters, like the following:

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

Moreover, Flask does not want you to call on these methods directly, they are intended to be executed only in response to a request input from Flask.

A better practice would be to abstract whatever logic you are trying to do into another function.

like image 26
jumbopap Avatar answered Feb 06 '26 09:02

jumbopap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!