Python flask to display remote user name in the web page - python

I am using below Python Flask code for reading remote user name in the web page.
and name = Request.remote_user.name is printing me REMOTE_USER as output can some one really tell me which particular configuration in web server i need to look at ? or how to get the real remote_user name into the web page.
from flask import Flask
from flask import Flask, render_template, Request, jsonify
app = Flask(__name__)
import flask
import os
import getpass
#app.route("/")
def hello():
return render_template('hello.html',name=name)
name =flask.Request.remote_user.name
if __name__ == "__main__":
app.run('localhost',8000)
and hello.html
<!doctype html>
<html>
<body>
<h1>Hello- {{ name }} </h1>
</body>
</html>

You can use
print(request.headers)
this will give you list of all session variables.
for getting a remote user
print(request.headers[X-Remote-User])

I guess we can use below code snippet initially to identify all headers and then the required one i.e. remote user
Identify all the Headers & values passed in the request
print("Headers: ", vars(request.headers))
for header in request.headers.items():
print(header)
then remote_user is available via key name X-Remote-User in the header.
remote_user = request.headers.get("X-Remote-User")
print("Remote User: ", remote_user)

Related

Problem loading a web app using flask, python, HTML and PostgreSQL; not able to connect python and html scripts plus Internal Server Error message

Recently, I have started working on a new project : a web app which will take a name as an input from a user and as result outputs the database rows related to the user input. The database is created using PostgreSQL and in order to complete the task I am using Python as a programming language, followed by Flask (I am new to it) and HTML. I have created 2 source codes, 1 in Python as below :
import os
import psycopg2 as pg
import pandas as pd
import flask
app = flask.Flask(__name__)
#app.route('/')
def home():
return "<a href='/search'>Input a query</a>"
#app.route('/search')
def search():
term = flask.request.args.get('query')
db = pg.connect(
host="***",
database="***",
user ="***",
password="***")
db_cursor = db.cursor()
q = ('SELECT * FROM table1')
possibilities = [i for [i] in db_cursor.execute(q) if term.lower() in i.lower()]
return flask.jsonify({'html':'<p>No results found</p>' if not possibilities else '<ul>\n{}</ul>'.format('\n'.join('<li>{}</li>'.format(i) for i in possibilities))})
if __name__ == '__main__':
app.run()
and HTML code :
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type='text' name ='query' id='query'>
<button type='button' id='search'>Search</button>
<div id='results'></div>
</body>
<script>
$(document).ready(function(){
$('#search').click(function(){
var text = $('#query').val();
$.ajax({
url: "/search",
type: "get",
data: {query: text},
success: function(response) {
$("#results").html(response.html);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
For these scripts I read the discussion here.
These scripts are giving me troubles and I have two main questions :
First : How are these two source codes connected to each other? whenever I run the python script or the html, they look completly disconnected and are not functioning.Moreover, when I run the Python script it gives me this error message on the webpage :
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
and this message on terminal :
Serving Flask app 'userInferface' (lazy loading)
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: off
Running on....
Can someone please help me by showing how can these 2 scripts connect and why am I getting such errors. Thank you.
You need to use render_template to connect Flask and your HTML code. For example:
from flask import render_template
#app.route("/", methods=['GET'])
def index():
return render_template('index.html')

Printing Data Received using POST Request to local server using Flask

So, apparently I am trying to send data from my openCV webcam to a local sever spun using Flask. I am able to receive the data and print it on terminal, however, I am not really sure as to how to print it on a webpage.
This is my program :
from flask import jsonify, Flask, make_response,request, render_template
from flask_restful import Resource, Api
# creating the flask app
from flask import jsonify, Flask, make_response,request, render_template
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
#app.route("/getData", methods=['POST', 'GET'])
def get():
if request.method == 'POST':
textInput = request.form["data"]
print(textInput)
return render_template("text.html",text=textInput)
else:
return render_template("text.html")
#app.route("/", methods=['GET'])
def contact():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
I am sending data from webcam.py using requests module via post request. The data is received and currently printed on terminal. However, I want it to be redirected to text.html.
data = {"data": res}
requests.post(url = API_ENDPOINT, data = data)
The above is the code snippet I use to send data from webcam.py to API_ENDPOINT (127.0.0.1:5000/getData).
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Sign to Speech</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html,
body {
background-color: #FFC107
}
</style>
</head>
<body>
<h4>{{text}}</h4>
</body>
</html>
The above is my text.html page under templates directory.
Any Help will be appreciated :D
The problem with your code is that you send data from OpenCV webcam to a local server and from local server you return a response to openCV webcam and that's why you see data in the terminal as you print it and you can't see data in the webpage of flask app as you don't have that data, because you have lost data at the moment you have returned a response to the openCV webcam.
In this case, you could use 1 of the 3 approaches.
Using a database, like sqlite3 and save received data from the openCV webcam, but then you will need to do more, like create models and etc.
Save data received from OpenCV webcam to a file - quicker option to verify that everything works (the one I will use in my code example)
Using flask.session and saving data to flask session and then reading from it as you would read data from python dictionary.
In these cases, when you open your flask web app in the browser, you need to read data from either DB, file or flask.session.
In this example, I will use a file named data.txt to which I will write (I will use a that means open file to append to the end of a file, then the old data will be left when you will send multiple requests from OpenCV webcam) information received from OpenCV webcam server.
from flask import Flask, request, render_template, jsonify
# creating the flask app
app = Flask(__name__)
#app.route("/getData", methods=['POST', 'GET'])
def getInfo():
if request.method == 'POST':
text_input = request.form["data"]
with open('data.txt', 'a') as data_file:
data_file.write(text_input)
return jsonify({'message': 'Data saved sucessfully!'}), 200
else:
text_input = None
with open('data.txt', 'r') as data_file:
text_input = data_file.read()
return render_template("text.html", text=text_input)
if __name__ == '__main__':
app.run(debug=True)
This way your OpenCV webcam will receive 200 response with a message. Then you can navigate to your web app /getData page, then the request method will be GET and then it will read the content of a file data.txt and will pass this to the webpage you have just opened.
Make sure that you can access data.txt, it should be placed in the same directory as your app exists (at least with this example, but you should make more appropriate structure later on or at all use the sqlite3 database for local development).
Try this below:
from flask import jsonify, Flask, make_response,request, render_template
from flask_restful import Resource, Api
# creating the flask app
app = Flask(__name__)
# creating an API object
api = Api(app)
#app.route("/getData", methods=['POST', 'GET'])
def getInfo():
textInput = request.form["data"]
print(textInput)
return render_template("text.html",text=textInput)
if __name__ == '__main__':
app.run(debug=True)
And in your HTML use Jinja like following below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
{{ text }}
</body>
</html>

Can't figure out what's wrong with my flask app when porting it from localhost

OVERVIEW
Hi, I have a Flask app that works on my localhost but not in pythonanywhere. My app basically does the following:
User fills out HTML form, hits submit
Script in HTML form uses jQuery $ajax to post to my flask app on sumbit
Flask app processes the data and sends it back to be displayed as HTML
Here are some things that I think might be wrong with my app when moving it to pythonanywhere:
urllib.requests might not be included in pythonanaywhere, I know urllib is included but I'm not sure if urllib.requests is different or just a part of urllib
On my localhost, my URL for $ajax was 'http:// 127.0.0.1:5000/ebaycode/', I couldnt find any info on what youre supposed to change this to after hours of looking so I tried 'http:// mander39.pythonanywhere.com/ebaycode/' which might be wrong
I have no idea what #app.route does and maybe this is messed up when moving to pythonanywhere
HTML CODE
<script>
$('#form').on('submit', function(e){
#random css changes with jQuery i.e. $('.box').css( "display","none")
#conditionals based on form data i.e. if ($('.checkbox').is(":checked"))
e.preventDefault();
$.ajax({
url: 'http://mander39.pythonanywhere.com/ebaycode/',
data: {'product': product, 'sold': sold, 'cond': cond},
method: 'POST',
success: function(data) {
#using $('#id').html to show my data output on my site
}
});
});
</script>
FLASK APP
from flask import Flask, render_template, request, jsonify
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
from statistics import mean
import numpy as np
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/ebaycode/', methods=['POST'])
def ebaycode():
prod = str(request.form.get('product', 0))
sold = str(request.form.get('sold', 0))
cond = str(request.form.get('cond', 0))
#whole bunch of other code
data = {'ebaycode': ebaycode,'lengthOne': lengthOne,'maxOne': maxOne,
'minOne': minOne,'avgOne': avgOne,'medOne': medOne, 'lengthTwo': lengthTwo,
'maxTwo':maxTwo, 'minTwo':minTwo,'avgTwo': avgTwo,'medTwo': medTwo, 'url': tac
}
data = jsonify(data)
return data
def reject_outliers(data, m = 3.):
#method called in ebaycode()
if __name__ == '__main__':
app.run(debug=True)
I wish I had a command prompt to show what my app is doing but bash and python cmd from pythonanywhere dont show anything. Thanks a bunch for the help, I really need it.

Problem about 500 Internal Server Error in Python Flask

This is my Python code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/profile/<name>")
def profile(name):
return render_template("index.html", name=name)
if __name__ == "__main__":
app.run()
and HTML code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Hello {{ name }}
</body>
</html>
And when I run the Python code, it shows on the browser that:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I looked for the solution on Google as well as Youtube, but still can't fix it. Can someone help me with this? Thank you
Edit: so all I need to do is to fix this one line:
app = Flask(__name__, template_folder="template")
Whenever we receive 500 internal server error on a Python wsgi application we can log it using 'logging'
First import from logging import FileHandler,WARNING
then after app = Flask(__name__, template_folder = 'template')
add
file_handler = FileHandler('errorlog.txt')
file_handler.setLevel(WARNING)
Then you can run the application and when you receive a 500 Internal server error, cat/nano your errortext.txt file to read it, which will show you what the error was caused by.
You must not had an empty line beetween
#app.route("/profile/<name>") and def profile(name):
You have to set the html file in a folder called templates.
You have to set the templates folder and run.py in the same folder
You can try this below by adding the type string in your #app.route :
#app.route("/profile/<string:name>")
def profile(name):
return render_template("test.html", name=name)

Post API-- what are the steps that need to be followed once the code is created so that I can add data into a txt file through this API

I am new to API, and get a tasks of creating POST API. I have created a code somehow.
I want to add data to the hello.txt through post API, So how will I do it?
Here is my code:
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/api/v1/resources/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/octet-stream':
return "Binary message written!"
elif request.headers['Content-Type'] == 'application/json':
f = open('F:\Asif_Ahmed\Projects\api\hello.txt',"w")
f.write(request.data)
f.close()
return "JSON Message: " + json.dumps(request.json)
else:
return "415 Unsupported Media Type ;)"
app.run()
from flask import Flask, jsonify, render_template, request #import flask library
from flask_basicauth import BasicAuth # import flask library for create basic authentication if needed
from flask_cors import CORS # import flask library Cross-Origin Resource Sharing that is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin
app = Flask(__name__)
CORS(app) #set-up cors for my app
#if you want use basic authentication you need set-up username and password
app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = 'password'
basic_auth = BasicAuth(app)#set-up username and password for my app but in this case I'm not specifying yet in which API use them
#app.route('/api/v1/resources/add_messages', methods=['POST'])#create my POST api
#basic_auth.required# set-up basic authentication for this API, comment out if not needed
def update_credential ():
json_credential=request.get_json()#get the JSON sent via API
print (json_credential["message"])#get the node "message" of my JSON
###########
#code to write in your file, you need write the json_credential["message"]
###########
return ("ok")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1024, threaded=True)#start my flask app with local_host IP and specific port, if you don't specify the port it will run in the default port
In this case the JSON Input should be:
{"message":"your text"}
Please let me know if something is not clear, I even try this code on my local and the JSON is passed without problems.....
So you need run your python script and see that the API is running, if you had no JSON to send and was just a simple API that give back information you should have used even Chrome but in this case that you need send some JSON data I would advice you to use Postman.
See screenshot example:

Categories

Resources