I have 2 functions in a single direction of page.
How to access both of them individually?
Now what's happening is, only 1st function is getting called.
The below program is a madeup prototype and my requirement builds on this logic.
from bottle import get,post,run,route,request
content1 = '''
<html>
<h1>Page 1 function </h1>
<form action='details' method='post'>
<input type = "text" name="uname">
<input type = "submit" >
</form>
</html>'''
content11 = '''
<html>
<h1>Page 2 function </h1>
<form action='details' method='post'>
<input type = "text" name="uname">
<input type = "submit" >
</form>
</html>'''
content2 = '''<html><h1>Hello %s </h1></html>'''
#get('/home')
def page1():
return content1
def page2():
return content11
#post('/details')
def page3():
u_name = str(request.forms.get('uname'))
return content2 %u_name
run(host='localhost', port=8080, debug=True)
The way you are asking the question implies you want to provide two separate web pages from the same address. REST doesn't work this way.
You need to provide a second route to access the code in page2()
Related
I have a configuration in my app that goes something like this:
#app.route("/path/<path:sub_path>", methods = ['GET'])
def path(sub_path):
print("Subpath is: " + str(sub_path))
return 1
And a form that looks something like:
<form role="form" class="" action="http://localhost:5000/path/<path:sub_path>" method="GET">
<input type="text" name="sub_path" id="sub_path" placeholder="Search 2..">
<input type = "submit" value = "submit" />
</form>
However, the print statement returns "Subpath is: <path:sub_path>".
How can I properly send the URL using the GET method?
I am trying to pass an input variable in a form tag to use in a python function. However, I keep getting different HTTP errors. I have changed the code numerous times drawing reference from other questions on the stack, none of them have worked.
The problem seems to be with the URL, the input variable appears in the URL but I may not be handling it correctly. I'm also getting an error sometimes with the 'attempted_question' not being recognized.
Any help appreciated
index.html
<html>
<head></head>
<body class = "body">
<body>
<form action="{{ url_for('about') }}" method=”PUT”>
<label> Enter population based question: </label>
<input name = "pop_question" >
<button type=”submit”> Submit </button>
</form>
<p> </p>
</body>
</body>
</html>
pass.html
<html>
<head></head>
<body class = "body">
<body>
<p> i am here {{ attempted_question }}</p>
</body>
</body>
</html>
</html>
run.py
from flask import Flask, render_template
#app.route("/")
def hello():
return render_template("index.html")
#app.route("/about", methods=['GET'])
def about():
living = request.form['pop_question']
return render_template('pass.html', attempted_question=living )
if __name__ == "__main__":
app.run(debug=True)
You use different http methods when sending and receiving data.
Try to use same method. 'POST' for example.
index.html
...
<form action="{{ url_for('about') }}" method=”POST”>
...
run.py
...
#app.route("/about", methods=['POST'])
...
I have an html file which reads like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Robots Uploader</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<section id="content">
<section class="module w100P">
<div id="error_bar" style = "display:none" class="message-bar error">
<p><span class="icon">Error:</span> Uh-oh, something broke! Close</p>
</div>
<div id="success_bar" style="display:none" class="message-bar success">
<p><span class="icon">Success:</span> Your changes have been made. Close</p>
</div>
<div class="module-inner">
<h3>DailyHunt Robots Uploader</h3>
<div class="module-content frm">
<form action="http://localhost:5000/uploadFile" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>
<select name ="domain">
<option selected>Select Domain</option>
<option value="m">m</option>
<option value="www">www/option>
</select>
</td>
<td>
<input type="file" name="robots" accept='robots.txt'>
<button type="submit">Upload</button>
</td>
</tr>
</table>
</form>
<form action="http://localhost:5000/uploadApk" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>
Enter APK you want to upload:
</td>
<td>
<input type="file" name="apk">
<button type="submit">Upload</button>
</td>
</table>
</form>
</div>
</div>
</section>
</section>
</section>
</body>
</html>
on hitting submit, it hits the flask api engine, where the 2 functions to be hit are defined as
#app.route('/uploadFile', methods=['POST'])
def upload_robots():
domain = request.form.get('domain')
if not domain:
return "Domain does not exist"
f = request.files[ROBOTS_IDENTIFIER]
if f.filename!=ROBOTS_FILE_NAME:
return "Incorrect file name. File name has to be robots.txt"
if domain == 'm':
robots_file_path = ROBOTS_MOBILE_FILE_PATH
elif domain == 'www':
robots_file_path = ROBOTS_WEB_FILE_PATH
else:
return "Domain not recognized"
filename = secure_filename(f.filename)
if os.path.isfile(robots_file_path + ROBOTS_FILE_NAME):
folder_name = datetime.utcfromtimestamp(int(os.path.getmtime(robots_file_path + ROBOTS_FILE_NAME))).strftime('%Y-%m-%d %H:%M:%S')
os.makedirs(robots_file_path + folder_name)
shutil.move(robots_file_path + ROBOTS_FILE_NAME, robots_file_path + folder_name +'/' + ROBOTS_FILE_NAME)
f.save(os.path.join(robots_file_path, ROBOTS_FILE_NAME))
return "file uploaded successfully, This will reflect in prod after the next cron cycle"
#app.route('/uploadApk', methods=['POST'])
def upload_apk():
f = request.files[APK_IDENTIFIER]
if f.filename.split('.')[-1] != 'apk':
return "upload file type must be apk"
filename = secure_filename(f.filename)
fname = '.'.join(f.filename.split('.')[0:-1])
rename = False
while os.path.isfile(APK_FILE_PATH + fname + '.apk'):
rename = True
fname += '_'
if rename:
shutil.move(APK_FILE_PATH + f.filename, APK_FILE_PATH + fname + '.apk')
f.save(os.path.join(APK_FILE_PATH, filename))
return "APK uploaded successfully"
Now when I hit submit the api returns some texts and it gets directed to a new page with just the text rendered. I would like this to remain in the same page and display the error_bar or success_bar divs in the html rather than it being redirected to a new page. Is it possible to achieve this without rendering a template or creating a new static html page?
Let's assume that your current page is: index.html.
I thought about two ways for resolving.
The first way,
After making request to your API, just render_template index.html again, including extra data (error=True/False, message=...) and you have update your index.html to check condition when receive extra data to display the error/success message.
=> By this way, you should modify the template and use Flask's render_template.
I prefer this way because of having control of the template (index.html) it just needs small update.
The second way, make request by using AJAX (XHR), when click submit button, you prevent the default form submit and use AJAX to request, then receive response and display the message.
The AJAX script can stay in index.html or another *.js where your index.html can locate.
=> By this way, you are working in non-Flask dependent way, by using Ajax you make request and modify the document (index.html) by using a little Javascript.
I have a Python script that uses Flask web framework to let users ask a question and depending on some certain questions, the application should ask back some questions to the user on a second webpage. The answers to the questions are evaluated based on the questions and displayed on the initial webpage.
model.py
### Importing Flask ###
from flask import Flask, render_template, request, session, redirect, url_for
### Initializing Flask ###
app = Flask(__name__)
#app.route('/')
def index():
return render_template('init.html')
#app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
### User Inputs Question ###
userQuestion = request.form['userQuestion']
def model():
message = "Depends on User"
if message == "Depends on User":
return render_template('user_information.html', userQuestion = userQuestion)
else:
message = "Your answer is ABC."
return message
message = model()
return render_template('init.html', userQuestion = userQuestion, message = message)
#app.route('/user_information', methods = ['POST', 'GET'])
def user_information():
userLevel = request.form['userLevel']
userDOJ = request.form['userDOJ']
userType = request.form['userType']
message = "Answer for Eligibility."
return render_template('init.html', userLevel = userLevel, userDOJ = userDOJ, userType = userType, message = message)
if __name__ == '__main__':
app.run()
These are my two HTML files:
init.html (initial webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
<!-- for-mobile-apps -->
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<br>
<p>Hi</p>
<form action="{{ url_for('handle_data') }}" method="post" class="agile_form">
<input type="text" name="userQuestion" placeholder="Ask your question..." required="">
<input type="submit" value="Submit">
</form>
<p>{{ message }}</p>
</div>
</div>
</body>
</html>
user_information.html (second webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<form action="{{ url_for('user_information') }}" method="post" class="agile_form">
<!--<input type="text" name="userName" placeholder="Enter your name." required="">-->
<input type="text" name="userLevel" placeholder="What is your level?" required="">
<input type="text" name="userDOJ" placeholder="What is your date of joining?" required="">
<input type="text" name="userType" placeholder="Are you on sabbatical or specialist?" required="">
<input type="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
When I execute my script and enters a question, what I get is the HTML code for user_information.html as my answer which is not what I want.
Ouput after I click Submit:
https://ibb.co/cwhRpk
Expected output after I click Submit:
https://ibb.co/c7CFh5
https://ibb.co/dX9T25
I can get the desired output if I remove the model() construct but that will make my code inefficient because in my actual application I have to call model() multiple times with different parameters.
Can anyone please suggest me what approach should I take? I'm totally stuck in this part. Thanks, any help is appreciated!
Your nested model() function does not make any sense at all. It returns the result of render_template, which is a complete response including HTTP headers etc. If you try and insert that into another template, Jinja will be forced to try and convert it to a string, which gives the result you see.
This is not at all the way to compose templates. Jinja supports template inheritance; you should call render_template once only, using a child template that inherits from a common base.
I am executing the following code.
import webapp2
form="""
<form method = "post">
What is your birthday?
<p>
<label>
Day
<input type = "text" name = "day">
Month
<input type = "text" name = "month">
Year
<input type = "text" name = "year">
</p>
<input type = "submit">
</form>
"""
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
def post(self):
self.response.out.write(form)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
When I try opening the page localhost:8080, I do not see anything. The page is empty.
I am not familiar with webapp2 but:
after a quick look to tutorials I have seen them write:
self.response.write(...) instead of self.response.out.write()
your code is not correctly indented, you should have:
def get(self):
self.response.write(form)
the string "form" does not seem like a valid html page
maybe you could try
<!DOCTYPE html>
<html>
<head>
<title>Whatever</title>
</head>
<body>
<form method = "post">
What is your birthday?
<p>
<label>
Day
<input type = "text" name = "day">
Month
<input type = "text" name = "month">
Year
<input type = "text" name = "year">
</p>
<input type = "submit">
</form>
</body>
</html>