My picture isnt showing, I tryed copying code and that didnt work. I want to be able to do this, what am i doing wrong?
my code
from bottle import route, run,Response,template
from bottle import *
import socket
temp=open("ht","r")
html1=temp.read()
temp=open("html2","r")
html2=temp.read()
#route("/")
def route1():
return html1
run(host=socket.gethostbyname(socket.gethostname()), port=8080, debug=True)
in html1
<img src="C:\Users\radbo\Desktop\discord bots\drago\chat\RUn\Servers\Turtle.png" width=290 length=100>
Use the template function to call your HTML so it is cached, then create a static path to your image file.
from bottle import route, run, response, request, template, static_file, get
#route("/")
def route1():
#this should be your full filename, like index.html
return template('ht')
#get('/static/<filepath:path>')
def _shared(filepath):
return static_file(filepath, 'C:\Users\radbo\Desktop\discord bots\drago\chat\RUn\Servers' )
run(host='127.0.0.1', port=8080, debug=True)
Then you can just do:
<img src="\static\Turtle.png" width=290 length=100>
Related
I'm currently trying to code something that will let websites view my webcam. I'm roughly following the tutorial linked on this website, except using Python and pygame instead of Processing.
At the moment, my code is grabbing a pygame image (which was originally a SimpleCV image), attempting to convert it into jpg format, and send it over websockets to the client where it will display it inside an img tag. However, I can't seem to figure out how to convert a pygame image into jpg and get it to display properly on the web browser.
This is my code for the server, which uses Flask and gevent:
#!/usr/bin/env python
import base64
import cStringIO
import time
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template
import pygame
pygame.init()
import SimpleCV as scv
app = Flask(__name__)
cam = scv.Camera(0)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/camera')
def camera():
if request.environ.get('wsgi.websocket'):
ws = request.environ['wsgi.websocket']
while True:
image = cam.getImage().flipHorizontal().getPGSurface()
data = cStringIO.StringIO()
pygame.image.save(image, data)
ws.send(base64.b64encode(data.getvalue()))
time.sleep(0.5)
if __name__ == '__main__':
http_server = WSGIServer(('',5000), app, handler_class=WebSocketHandler)
http_server.serve_forever()
This is my HTML file:
<!DOCTYPE HTML>
<html>
<head>
<title>Flask/Gevent WebSocket Test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
if ("WebSocket" in window) {
cam = new WebSocket("ws://" + document.domain + ":5000/camera");
cam.onmessage = function (msg) {
$("#cam").attr('src', 'data:image/jpg;base64,' + msg.data);
};
cam.onerror = function(e) {
console.log(e);
}
} else {
alert("WebSocket not supported");
}
});
</script>
</head>
<body>
<img id="cam" src="" width="640" height="480" />
</body>
</html>
These are the specific lines that I think I'm having trouble with:
while True:
image = cam.getImage().flipHorizontal().getPGSurface()
data = cStringIO.StringIO()
pygame.image.save(image, data)
ws.send(base64.b64encode(data.getvalue()))
time.sleep(0.5)
Currently, if I try and run my code, going to localhost:5000 will display an invalid jpg image. It also becomes really laggy if I try running it on Firefox, but that may be an unrelated issue that I can debug later.
I've checked and made sure that the pygame image is a valid one, since I'm converting it from another library, and also checked that I was using websockets correctly by sending text data back and forth.
I've also tried calling pygame.image.to_string to try and convert the pygame surface into RGB format, but that also doesn't work.
What am I doing wrong?
Using the underlying PIL image, we can write to a file-like object, read back and base-64 encode it:
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, request
from time import sleep
from cStringIO import StringIO
import pygame
pygame.init()
import SimpleCV as scv
app = Flask(__name__)
cam = scv.Camera(0)
#app.route('/camera')
def camera():
if request.environ.get('wsgi.websocket'):
ws = request.environ['wsgi.websocket']
while True:
fp = StringIO()
image = cam.getImage().flipHorizontal().getPIL()
image.save(fp, 'JPEG')
ws.send(fp.getvalue().encode("base64"))
#fp.close() << benchmark and memory tests needed
sleep(0.5)
if __name__ == '__main__':
http_server = WSGIServer(('',5000), app, handler_class=WebSocketHandler)
http_server.serve_forever()
I'm fighting with the same issue and the problem is a double codification. In the Python file, you have to remove the line "ws.send(base64.b64encode(data.getvalue()))" and send the image without encoded. Then in the js file, your script will make the codification and that all.
I'm using Flask-Misaka with Flask to render a markdown string to html. However, it seems that the Flask-Misaka can't recognize fenced code. It does removed the back-ticks, but no colored block is displayed. I have tried with versions 0.4.0 and 0.4.1.
app.py
from flask import Flask, render_template
from flask_misaka import Misaka, markdown
app = Flask(__name__)
Misaka(app, fenced_code=True)
TEST_MD = markdown("```block```\n", fenced_code=True)
#app.route("/", methods=['GET'])
def index():
return render_template('{{s|markdown}}', s=TEST_MD)
The issue is that you are missing a stylesheet. If you look at the HTML output of Flask it will show <p><code>block</code></p>\n. So the fenced code is seen and the HTML output is rendered correctly.
Short example which directly shows the result when the code is executed:
from flask import Flask, render_template_string
from flask_misaka import markdown
app = Flask(__name__)
with app.app_context():
render_template_string('{{s}}', s=markdown("```block```\n", fenced_code=True))
I'm trying to write a web application and am using Tornado Web for the json xhr calls. But I'm trying to serve a static index.html which is to serve the main app.
How can I serve a simple page and still have requesthandlers for the rest of my application?
Here's what I tried so far:
import tornado.ioloop
import tornado.web
import json
import os
games = [...]
class HomeHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class MatchHandler(tornado.web.RequestHandler):
def get(self):
self.write(json.dumps(games))
path = os.path.join(os.getcwd(), 'app')
if __name__ == "__main__":
application = tornado.web.Application(
[
(r'/', HomeHandler),
(r'/games', MatchHandler),
(r'/*.*', tornado.web.StaticFileHandler, {'path': path})
],
template_path=os.path.join(os.path.dirname(__file__), 'app')
)
application.listen(16001)
tornado.ioloop.IOLoop.current().start()
Thanks in advance!
The StaticFileHandler regex needs to A) contain a capturing group and B) use regex syntax instead of glob syntax:
(r'/(.*\..*)', tornado.web.StaticFileHandler, {'path': path})
This will match any paths containing a dot and send it to the StaticFileHandler.
Your code looks correct to me. Put a file named "index.html" in the "app" subdirectory of your current working directory when you run the app, and the contents of that "index.html" will be the response when you visit http://localhost:16001/
Your code should work fine, as #a-jesse-jiryu-davis answered. To expand a bit on it, you could use tornado.web.StaticFileHandler if you just need to serve your static file. This will make it more flexible, and also take advantage of server-side caching etc.
I'm trying to run a Python script with HTML code embedded and it's not working. I'm want to execute a Python script and at the same time render the HTML which will be printed by the script.
app.py:
#!/usr/bin/python2.6
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/briefing')
def briefing():
return render_template('briefing.html')
#app.route('/briefing/code')
def app_code():
return render_template('app_code.py')
if __name__ == '__main__':
app.run(debug=True)
app_code.py:
http://i.stack.imgur.com/sIFFJ.png
When I access http://127.0.0.1:5000/briefing/code the result is http://i.stack.imgur.com/iEKv2.png.
I know that what is happening is that I'm rendering as HTML and therefore the Python code inside of the file is not being interpreted.
How can I run the app_code.py and at the same time, render the HTML from it?
You are mixing up a lot of things, I saw the first post of the question took me a while to figure out what you are trying to do.
The idea that you seem to need to grasp is that, you'll need to prepare the model in Python first (e.g. a string, an object, a dict etc with the data you want), and then inject it into a template to be rendered (as opposed to printing out what you want to see in the HTML output)
If you want to display the output from a subprocess.call into an HTML page, here's what you should do:
Get the output from subprocess in a string format
Create a HTML template to display it in
Make Flask call the subprocess, render the template and return the HTTP response
app.py:
#!/usr/bin/python2.6
import subprocess
from flask import Flask, render_template
app = Flask(__name__)
def get_data():
"""
Return a string that is the output from subprocess
"""
# There is a link above on how to do this, but here's my attempt
# I think this will work for your Python 2.6
p = subprocess.Popen(["tree", "/your/path"], stdout=subprocess.PIPE)
out, err = p.communicate()
return out
#app.route('/')
def index():
return render_template('subprocess.html', subprocess_output=get_data())
if __name__ == '__main__':
app.run(debug=True)
subprocess.html:
<html>
<head>
<title>Subprocess result</title>
</head>
<body>
<h1>Subprocess Result</h1>
{{ subprocess_output }}
</body>
</html>
In the above template, {{ subprocess_output }} will be replaced by the value you pass from your Flask view before the resulting HTML page is sent to the browser.
How to pass more than one value
You can either render_template('page.html', value_1='something 1', value_2='something 2')
and in the template: {{ value_1 }} and {{ value_2}}
Or you can pass a dict called e.g. result:
render_template('page.html, result={'value_1': 'something 1', 'value_2': 'something 2'})
and in the template {{ result.value_1 }} and {{ result.value_2 }}
I'm working on a python app in Python Bottle. The app works fine if I'm on 1 lvl deep URLs like /dashboard or /rules or /page. However, if I go deeper like /dashboard/overview or /rules/ruleone or /page/test the CSS, JS, fonts and images will fail. :(
The HTML source code still poinsts to /assets/ but if I'm on an URL like /rules/ruleone, the right path should be something like ../assets or ./assets right? The path /assets/ only works on the first level but not on deeper lvls, in other words: bottle doesnt adapt the static file path to the current directory. How do I fix this?
I'm stuck on this problem for days now, I realy hope someone can help me. :(
My code (simplified):
#!/usr/bin/env python
import lib.bottle as bottle
from lib.bottle import route, template, debug, static_file, TEMPLATE_PATH, error, auth_basic, get, post, request, response, run, view, redirect, SimpleTemplate, HTTPError, abort
import os, sys, re
#route('/dashboard')
#view('secure_page')
def show__page_dashboard():
return dict(page = 'Dashboard')
#route('/rules/<rule>')
#view('secure_page')
def show_page_rules_more(rule):
return dict(page = rule)
#route('/assets/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='/var/myapp/assets')
TEMPLATE_PATH.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "view")))
bottle.debug(True)
from lib.bottledaemon import daemon_run
if __name__ == "__main__":
daemon_run()
So my app runs in daemon mode. The structure is:
lib
bottle.py
bottledaemon.py
assets
css
js
...
view
secure_page.tpl
footer.tpl
header.tpl
...
server.py
I hope someone can help me out on this, thanks in advance guys, I love u! <3
Alright I found the solution for my problem. Bottle offers an URL tag to dynamicly build URLs.
from bottle import url
#route('/dashboard')
#view('secure_page')
def show__page_dashboard():
return dict(page='Dashboard', url=url)
#route('/assets/<filepath:path>', name='assets')
def server_static(filepath):
return static_file(filepath, root='/var/myapp/assets')
This is how I load my CSS/JS/images
<link href="{{ url('assets', filepath='css/style.css') }}" rel="stylesheet" type="text/css"/>
Dynamic menu URL's (in the navigation for example) is done this way:
{{ url('/dashboard') }}
I hope this info will help someone who is strugling with the same problem as I was.
Tested on v0.12 and v0.13dev
I do use:
#route('/css/<filename>')
def stylesheets(filename):
return static_file(filename, root='./static/css/')
and in template use:
<link href="/css/style.css" rel="stylesheet">
can be replicated for all assets items (img, css, and js)