When I run the following simple piece of python / flask I do not get the entire string passed through to the html page - instead of "hello this is simon" I get "hello"
I am working on Python 3.4.2
I thought it might be something to do with encoding but I have tried everything I can think of with encoding and still no joy. Any help gratefully received :)
This is the python file (testit.py)
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def init_logon():
email = "hello this is simon"
return render_template("testit.html", email=email)
if __name__ == '__main__':
app.debug = True
app.run()
This is the simple template (testit.html)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" value={{ email }}>
</p>
</body>
</html>
The out put from a number of browsers is all the same: the text is truncated at the first white space
All that is displayed in my browser is:
"hello" - none of the text after the first white space is passed through
apologies I am not allowed to post the image I created :(
In your HTML, you didn't quote the attribute value, so the result of your template is
<input type="text" name="email" id="email" value=hello this is simon>
That means only the "hello" is the value of the "value" attribute. You should be able to see this if you look at the source of the generated page.
You could change your template so it has value="{{ email }}".
Related
I am trying to read a csv attachment using python requests.get method with oAUTH token. Its working fine in postman but not from from my program.
I am trying to use below code
import requests
def callF():
url = "https://jiraurl.com/secure/attachment/26433/Bulk_Repo_Archival_SMDH.csv"
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkpKRmRuSURYTngt"
jira_headers = {"Authorization":str(token)}
#print(jira_headers)
data = requests.get(url,headers= jira_headers,verify=False)
print(data.content)
if __name__ == '__main__':
callF()
I am getting below response:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body onload="document.forms[0].submit()">
<noscript>
<p>
<strong>Note:</strong> Since your browser does not support JavaScript,
you must press the Continue button once to proceed.
</p>
</noscript>
<form action="https://idag2.jpmorganchase.com/adfs/ls/" method="post">
<div>
<input type="hidden" name="RelayState" value="-ZIP8P-/secure/attachment/2226433/Bulk_Repo_Archival_SMDH.csv"/>
<input type="hidden" name="SAMLRequest" value="PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDJwOkF1dGhuUmVxdWVzdCB4bWxuczpzYW1sMnA9InVybjpvYXNpczpuYW1lczp0Yz"/>
</div>
<noscript>
<div>
<input type="submit" value="Continue"/>
</div>
</noscript>
</form>
</body>
</html>
However in postman also it gave same response for me for sometime but later somehow it is giving proper csv file data. I tried checking in multiple places but no luck. FYI it was working fine when we used basic authentication but after shifting to oAUTH its not working.
Please help.
I am able to resolve this by using below code:
from jira import JIRA
from jira_oauth import get_access_token
username = 'A12345'
jira_access_token = get_access_token()
download_folder = "downloads/"
server = "https://jira.prod.aws.net"
jira = JIRA(basic_auth=(username, jira_access_token), options={'server': server,'verify': False})
issue = jira.issue('DEVSERVOPS-11111', fields='summary,comment,attachment')
for attachment in issue.fields.attachment:
with open(download_folder + '%s' % (attachment.filename), 'wb') as file:
file.write(attachment.get())
This question already has answers here:
How to debug a Flask app
(14 answers)
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 4 years ago.
So, what I want to do is read 2 csv files, send them over my app.py and then print the results in a new HTML using Flask. Problem is, I can't find what I'm doing wrong. To be more specific I'm sending my CSV files through my app.py and I get either internal errors (500) or server errors (404) one after the other and I don't have a syntax error so it MUST be logical. So, what can I do to fix that because I'm at square one and my gut says that is as trivial as they come.
app.py:
from flask import Flask, render_template, request
import numpy
import pandas
import jinja2
app = Flask(__name__)
#Create a route to a file which is called "/" and uses both GET and POST
#app.route('/', methods=['GET', 'POST'])
#define function send
def results():
#retrieve data from form where we used POST
if request.method == 'POST':
table1=request.files['table1']
table2=request.files['table2']
#define function
def new_t(t1,t2):
#Combine t1 and t2
t3=np.hstack((t1,t2))
return(t3)
results=new_t(t1,t2)
#sends input to the template results.html with the inherited value "results"
return render_template('/results.html', results=results)
#in case there was a mistake we are redirecting the user to index.html
return render_template('/index.html')
index.html:
<!DOCTYPE html>
<html>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<body>
<h1>Give to your CSVs: </h1>
<!-- Create a form that sends data to our server (in this case local) using POST method -->
<form method="POST" action="/results" enctype="multipart/form-data" >
<!-- Style our input using Bootstrap CSS -->
<div class="form-group">
<!-- Create an input with type text so we can type our age in text form -->
<b>Choose Table1 (CSV format):</b>
<input type="file" name="table1">
<b>Choose Table2 (CSV format):</b>
<input type="file" name="table2">
</div>
<!-- Create and style our submit button-->
<input class="btn btn-primary" type="submit" value="submit">
</form>
</body>
</html>
results.html
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<!-- Print out the age that we typed which was sent from our app.py -->
<h1>Results: </h1>
<table>
{{ results|safe }}
</table>
</body>
</html>
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 attempting to log into a very simple web interface. This should involve entering and submitting a passcode; I don't expect to need to keep track of cookies and there is no username.
The web page is like the following, with a simple form for POSTing the passcode:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- saved from url=(0039)http://start.ubuntu.com/wless/index.php -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Wireless Authorisation Page</title>
</head>
<body>
<h1>Title</h1>
<h2>Wireless Access Authorisation Page</h2>
Hello<br>
<form action="http://start.ubuntu.com/wless/index.php" method="POST"><input type="hidden" name="action" value="auth">PIN: <input type="password" name="pin" size="6"><br><input type="submit" value="Register"></form>
<h3>Terms of use</h3><p>some text</p>
</body>
</html>
I have attempted the following using urllib and urllib2:
import urllib
import urllib2
URL = "http://start.ubuntu.com/wless/index.php"
data = urllib.urlencode({"password": "verysecretpasscode"})
response = urllib2.urlopen(URL, data)
response.read()
This hasn't worked (the same page is returned and login is not successful). Where might I be going wrong?
The form has two named input fields, you're only sending one:
<form action="http://start.ubuntu.com/wless/index.php" method="POST">
<input type="hidden" name="action" value="auth">
PIN: <input type="password" name="pin" size="6"><br>
<input type="submit" value="Register">
</form>
The second one is called pin, not password, so your data dict should look like this:
{"pin": "verysecretpasscode", "action": "auth"}
You might want to try using something like requests
This allows you to
import requests
print(requests.post(url, data={"password": "verysecretpasscode"}))
Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code,
here is the HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Admin Login</title>
</head>
<body>
<big><big>Login
Here<br>
<br>
</big></big>
<form action="/var/www/cgi-bin/Login.py" name="LoginForm"><big>Administration
Login<br>
User Name<br>
<input name="UserName"><br>
<br>
<br>
Password<br>
<input name="PassWord"><br>
</big><br>
<br>
<br>
<input type="submit">
<br>
</form>
__ <br>
</body>
</html>
and the python code..
#!/usr/bin/python
import cgi
import cgitb; cgitb.enable()
# get the info from the html form
form = cgi.FieldStorage()
#set up the html stuff
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Myusername' and Pass == 'MyPasword':
print '<big><big>Welcome'
print 'Hello</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The problem is, when i submit the username and password, it just shows the whole code back on the browser and not the required Welcome message :(. I use Fedora13 .. can anyone tell me what is going wrong? I even changed the permissions of the file(s).
Most likely, your webserver is not configured to execute the script. Even if it's marked as 'executable' in the file system, that doesn't necessarily mean the webserver knows that it should be executing .py files (rather than just serving them 'straight up'). Have a look here if you're running Apache: http://httpd.apache.org/docs/2.0/howto/cgi.html
<form action="/var/www/cgi-bin/Login.py" name="LoginForm">
Try
<form action="/cgi-bin/Login.py" name="LoginForm">
/var/www is probably the path from your ftp site. The web server will only look inside /var/www, so it puts that part there automatically.