I am using flask to run my python code when html button is pressed. My python code takes an encoded image and returns the encoded text by decoding it.Now what I want is when html button is pressed, the page runs the python code and shows me the decoded text but when html button is pressed the webpage only shows the code in my py file but not runs it.
This is the python "new.py" code:
from flask import Flask
import os
import subprocess
app = Flask(__name__)
#app.route("/stop/")
def test():
os.system('Python CN_Project.py')
if __name__ == "__main__":
app.run(debug=True)
I am a beginner in networks ans python. Please help me.
Have you tried going through the Flask tutorial yet to get something simple working?
In the template, you can create a link to a python function:
log in
Yours would look like:
stop
And then in your view, new.py, import your python file as a module and call the function in there that decodes the image and returns the text.
from flask import Flask
from CN_Project import decode_text_from_image
...
#app.route("/stop/")
def test():
output_text = decode_text_from_image('hardcoded_image.jpg')
return render_template('my_page.html', text_to_render=output_text)
...
Then you want to render the output text in your html template:
<p>{{ text_to_render }}</p>
For now, work on just using an image that is hardcoded into your python function. Afterwards, you can deal with passing in the image, maybe through a filepicker.
References:
Flask tutorial
Flask templates
Flask view functions
Related
I am doing an assignment to integrate a python script with HTML templates, and while the IDE is giving me no errors, when I try to actually run the website it gives me an "internal server error" and in the debug menu it says either that it doesn't recognize the Flask command "render_template" or doesn't recognize the HTML file it's supposed to render. The HTML file is stored both in the same folder as the python file and a copy is stored in a seperate "templates" folder located in the same folder as the python file. I really have no idea what's going on, the teacher has been no help.
I tried renaming the files, spell checked the imports repeated, checked all the commands, made copies of the python and Html files to see if the directorry was the problem. I really am not sure what else to try
...from flask import Flask
...from flask import render_template
...from flask import request
...from flask import flash
...import datetime
...app = Flask(__name__)
```#app.route('/')
...#the home page
...def home():
... return render_template('home_page.html')
```#app.route('/clock/')
...#the clock site
...def time_site():
... return date_and_time()
...def date_and_time():
... cur_time = str(datetime.now())
...return render_template('clock.html', cur_time)
```if __name__ == "__main__":
...app.run()
This question already has answers here:
Serve static files from a CDN rather than Flask in production
(3 answers)
Closed 1 year ago.
I'm using a web server on PythonAnywhere to run a Flask application. All I'm looking to do is randomly output a gif from a list of URLs. I'm looking to utilize the requests library, and I suspect I need the render_template in order to actually pass the image over. I have been dealing with either view function TypeErrors or outputs of plain text to a URL. I've also incorporated PIL and shutil once or twice but to no functional success.
from flask import Flask, render_template
import random
import requests
app = Flask(__name__)
WELCOME_LIST = [
'https://cdn.discordapp.com/attachments/891856529928622080/891865614870806568/rgb.gif'
'https://cdn.discordapp.com/attachments/891856529928622080/891865655542964224/racing.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891897881550802954/comet.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891897942678581278/harujion.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898027126698045/letter.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898085909864479/encore.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898143627677786/gunjou.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898187240050718/haruka.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898241900236830/monster.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898276339646474/probably.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898352617259028/taisho.gif',
'https://cdn.discordapp.com/attachments/891856529928622080/891898425342316624/tracing.gif',
]
#app.route('/')
def obtainGif():
gif = random.choice(WELCOME_LIST)
response = requests.get(gif)
return response.raw
#app.route('/join')
def output():
finalize = obtainGif
return render_template('home.html', finalize=finalize)
if __name__ == '__main__':
app.run(host='0.0.0.0')
Use the send_file method.
from flask import Flask, render_template, send_file
def obtainGif():
gif = random.choice(WELCOME_LIST)
response = requests.get(gif, stream=True)
return send_file(response.raw, mimetype='image/gif')
You can use {{ variable }} anywhere in your template, not just in the HTML part.
def output():
gif = random.choice(WELCOME_LIST)
return render_template('home.html', gif=gif)
in the home.html file add a script tag in which you are capturing this passed data
<script>
let gif= {{gif|safe}};
</script>
At this point you have the GIF URL inside your java-script code from where you can edit the HTML part of your code to add this GIF inside the <img> tags
So I have been trying to get used to Flash in python but I've come across a problem. I want that when http://localhost:5000/ is inserted in the browser a html page is displayed. I've tried multiple ways to do this like using the render_template() but that returns me a jinja2.exceptions.TemplateNotFound: index.html. I've also tried a simple return redirect() but that throws something saying the adress was not recognized or understood. When I tried using the url_for() it threw 404 - not found. I really have no idea how to fix this.
# htppserver.py
import flask
import threading
app = Flask(__name__, template_folder="Dashboard/website")
#app.route("/site", methods=["GET"])
#app.route("/", methods=["GET"])
def get_site():
return render_template("index.html")
x = threading.Thread(target=app.run)
x.start()
Currently my dir system looks something like this
main_folder # This is the working directory accordingly to os.getcwd()
├──cogs
│ └──httpserver.py # Source code is here
└──Dashboard
└website
├──...
├──index.html # This is the file I want to show
└──...
Thanks
put your html files in a folder called "templates" in the same directory as the python file that serves
this allows me to connect to a website with python on my computer:
from twill.commands import go, show, showforms, formclear, fv, submit
from bs4 import BeautifulSoup as bs
go('http://www.pge.com')
showforms()
this gets me to hello world on google app engine, with the twill and beautiful soup imports working:
import webapp2
import sys
sys.path.insert(0, 'libs')
from twill.commands import go, show, showforms, formclear, fv, submit
from bs4 import BeautifulSoup as bs
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello, World! I love dog food.')
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
now after this i try to connect to a website using twill and fail:
where can i call go() to connect to a website?
if I add it before class MainPage(webapp2.RequestHandler): it hangs and I don't get to hello world.
If I add it inside the MainPage class on the first line as either getit = go('http://www.pge.com'), or just go('http://www.pge.com'), it also hangs and I don't get to hello world.
If I add it inside def: get(self):, I get:
Internal Server Error
The server has either erred or is incapable of performing the
requested operation.
and a bunch of stuff about twill and mechanize.py, followed by
File "..../twill/utils.py", line 275, in run_tidy
process = subprocess.Popen(_tidy_cmd, stdin=subprocess.PIPE,
AttributeError: 'module' object has no attribute 'Popen'
am i somehow missing some other dependencies, like mechanize.py? or is there something else i need to be doing?
This helped partially solve my issue, but other problems cropped up later, particularly in filling forms, submitting them, and migrating further in the website.
import webapp2
import sys
sys.path.insert(0, 'libs')
from twill.commands import go, show, showforms, formclear, fv, submit, config
from twill.browser import *
from bs4 import BeautifulSoup as bs
class MainPage(webapp2.RequestHandler):
config('use_tidy', '0')
def get(self):
go('http://www.pge.com')
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello, World! I love dog food.')
self.response.write(show())
tidy is disabled in this way (tidy does not play well with the google sandbox), and I am able to show() the webpage via self.response.write(show()).
As a side note: be careful about using TextEdit to edit .py files when working with google app engine. I was getting all sorts of weird non-ascii character errors. I added # -- coding: utf-8 -- to the first line of the python file, which sort-of helped, and switched to using pycharm's ide which really helped.
twill is giving me all sorts of issues inside google app engine's sandbox that i am not getting on my system. i can get finally the html for one webpage, but can't submit forms in the way i was doing so simply on my system. showforms() isn't even showing the forms, maybe because i disabled tidy and the html is not being parsed properly?
i think one way to move forward here is to get tidy to work inside twill. obviously roadblocks are being hit "under the hood", and they are hard for me to see.
it seems like twill is a high level abstraction and maybe is not a good idea right now for using on google app engine. next i will try to switch to mechanize.py, or look for another sandbox, maybe amazon?
I am new to Python and Web.py, but I am tearing my hair out over this issue. I have a code layout where I have my app.py file in the root of my site. All the pages are in a sub director, named pages. Here is my app.py code
import web
import page.index
urls = (
'/', 'page.index.index',
)
render = web.template.render('templates/', base = "layout") # Start the template
app = web.application(urls, globals()) # Start the app
if __name__ == "__main__":
app.run()
Now, it executes perfectly. Now, in the index.py file, this is my code:
class index:
def GET(self):
testing = 'Hello World'
return render.index(testing)
The error I am getting is this:
<type 'exceptions.NameError'> at /
global name 'render' is not defined
Python /Volumes/Local Disk 2/Work/Casting Board/com/index.py in GET, line 3
Web GET http://127.0.0.1:8080/
Basically, I am trying to access the function ( or it is method or class. Just coming from PHP so don't know the terminally) render from a moucle called page.index. How can I get around this?
In the index.py page, should you include from web.template import render ?
Presuming web.template.render() returns an object containing an index() method (I'm not familiar with web.py), you'll need to tell Python where to find this object.
In index.py:
import app
Then:
return app.render.index(testing)
You can just include you index class (index.py) within your app.py file. Importing the web module then will bring in the definition of the function "render" at the beginning of your code.