To list all properties/methods of an object, use dir function.
inst = ClassA()
dir(inst) ##to list all properties/methods of object
We can read a dictonary object elements using get method.
##reading dictionaries:
r = ('greeting': 'hello')
type(r) # dict
r.get('greeting')
Similarly, the REQUEST data sent from client browser, will be received as REQUEST object and its contents are acessed using the python get method.
How data is passed by client.
www.abc.com/?greeting=hello
part after / is the query string.
And the key/value pairs are parameters
REQUST object:
1. context variable
2. holds the GET request details
3. python dictionary with key-value pairs
localhost:5000/new/?greeting=hello
The above data is passed using REQUEST object to below code.
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/index')
@app.route('/')
def hello_flask():
return 'Hello flask!'
@app.route('/new/')
def query_strings(greeting):
query_val = request.args.get('greeting')
return '<h1> the greeting is : {0} </h1>'.format(query_val)
if __name__ == '__main__':
app.run(debug=True)
The REQUEST object is accessed using request in flask library imported.
We can set a default value in the python code so that if user didn't pass data, we can use the default value.
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/index')
@app.route('/')
def hello_flask():
return 'Hello flask!'
@app.route('/new/')
def query_strings(greeting = 'default_value'):
query_val = request.args.get('greeting', greeting) # second arg is optional to pass default value
return '<h1> the greeting is : {0} </h1>'.format(query_val)
if __name__ == '__main__':
app.run(debug=True)
we can use variables in query url itself instead of passing query strings.
@app.route('/user')
@app.route('/user/name')
def no_query_strings(name='mina'):
return '<h1>hello there! {}</h1>'.format(name)
The url to test:
localhost:5000/user/testuser
No comments:
Post a Comment