I wrote a python test program like this to show openstreetmap:
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
def mainPyQt5():
url = 'file:///./index.html'
app = QApplication(sys.argv)
browser = QWebEngineView()
browser.load(QUrl(url))
browser.show()
sys.exit(app.exec_())
mainPyQt5()
index.html fetched by QWebEngineView simply calls openstreetmap:
<title>OSM and Leaflet</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<div id = "map" style = "width: 900px; height: 580px"></div><script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script>
// Creating map options
var mapOptions = {
center: [45.641174, 9.114828],
zoom: 10
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
</script>
If I fetch index.html with a ordinary browser the map is shown as expected but if I call the simple python program using QWebEngineView no tiles are downloaded from openstreetmap. If I replace openstreetmap with maps.stamen.com everything is fine both with a browser or the python script.
By default QtWebEngine does not set default headers like popular browsers do. In this case the openstreetmap server needs to know the "Accept-Language" to produce the maps since for example the names of the cities will depend on the language to filter non-browser traffic. The solution is to implement a QWebEngineUrlRequestInterceptor that adds that header:
import os.path
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor
from PyQt5.QtWebEngineWidgets import QWebEngineView
class Interceptor(QWebEngineUrlRequestInterceptor):
def interceptRequest(self, info):
info.setHttpHeader(b"Accept-Language", b"en-US,en;q=0.9,es;q=0.8,de;q=0.7")
def mainPyQt5():
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(CURRENT_DIR, "index.html")
app = QApplication(sys.argv)
browser = QWebEngineView()
interceptor = Interceptor()
browser.page().profile().setUrlRequestInterceptor(interceptor)
browser.load(QUrl.fromLocalFile(filename))
browser.show()
sys.exit(app.exec_())
if __name__ == "__main__":
mainPyQt5()
Related
The data i entered in the admin page not showing up on the web page.
i don't know what is going wrong with my code, please help
webpage
admin.py
from django.contrib import admin
from blog.models import Post
# Register your models here.
class PostAdmin(admin.ModelAdmin):
list_display = ('title','slug','status','created_on')
list_filter = ('status',)
search_fields = ['title','content']
prepopulated_fields = {'slug':('title',)}
admin.site.register(Post, PostAdmin)
urls.py
from . import views
from django.urls import path
urlpatterns = [
path('blogspot/',views.PostList.as_view(), name="b"),
path('<slug:slug>/',views.PostDetail.as_view(), name="post_detail"),
]
views.py
from django.views import generic
from .models import Post
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'
I'm trying to send a string from combobox to an api. Unfortunately nothing is being sent.
main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: mainWindow
width: 1120
height: 680
visible: true
Rectangle {
id: mainBody
color: "#F4F4F5"
anchors.fill: parent
ComboBox {
id: comboBox
x: 219
y: -9
width: 504
height: 40
model: [ "hp", "lenovo", "acer"]
}
Button {
id: bt
width: 24
height: 24
onClicked: backend.add(comboBox.text)
}
}
Connections {
target: backend
}
}
main.py
# This Python file uses the following encoding: utf-8
import os
# from pathlib import Path
import sys
import json
import requests
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import Slot, Signal, QObject
class MainWindow(QObject):
def __init__(self):
QObject.__init__(self)
signalcombo = Signal(str)
#Slot(str, str, str)
def add(self, getCombo):
putdata1 = {"category_name": getCombo}
data1 =
requests.post("random api", json=putdata1)
print(data1.text)
if __name__ == "__main__":
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
# engine.load(os.fspath(Path(__file__).resolve().parent / "qml/main.qml"))
engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))
# Get Context
main = MainWindow()
engine.rootContext().setContextProperty("backend", main)
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
Now the problem is that when data1.text is printed it says "Inserted Successfully", but there is nothing in the database not even blank space. No data is being sent. Can anyone help me. This approach is working for textField but not for combobox.
There are various problems with your code.
First of all, the slot decorator for add has the wrong number of arguments. In the QML you're calling it with only one argument, but the slot has three. Change it to:
#Slot(str)
def add(self, getCombo):
# ...
Then, ComboBox has no property named text, but currentText (or any other valid property available for it, like displayText).
Button {
id: bt
width: 24
height: 24
onClicked: backend.add(comboBox.currentText)
}
Finally, while not critical, you should first set the context, and then load the QML:
main = MainWindow()
engine.rootContext().setContextProperty("backend", main)
engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))
I am using bokeh and panel to create an animated plot together with some navigation controls like a slider, play/pause, skip 5s, etc.
At the same time, there is video footage which I would like to display in sync with that animation. I started playing around with dash.js and managed to prepare the video accordingly and display it in a standalone page. (yay!)
Since I don't know much javascript, I was wondering: Is there a solution out there for synchronizing these two things?
(A dream scenario: A panel widget for displaying and controlling a dash.js video player from python. Well, one can hope, right? But I'll take any hints, advice, ideas.)
Answering my own question, just in case it may save anyone a bit of trial&error.
After walking into a few dead ends, I wrote a small custom bokeh widget that does what I need.
Here's the code:
from bokeh.core.properties import Bool, String, Float
from bokeh.models import Div
DASH_URL = <url to the dash.js lib>
JS_CODE = """
import * as p from "core/properties"
import {Div, DivView} from "models/widgets/div"
declare var dashjs: any
export type DashViewerData = {from: number, to: number}
export class DashViewerView extends DivView {
model: DashViewer
private video_el: HTMLElement
private player: any
render(): void {
super.render()
this.video_el = document.createElement('video')
this.video_el.id = this.model.video_element_id
this.video_el.setAttribute('width', "1120px")
this.video_el.setAttribute('height', "630px")
this.video_el.setAttribute('controls', '')
this.el.appendChild(this.video_el)
this.el.appendChild(document.createTextNode(this.model.url))
document.createElement('script')
this.player = dashjs.MediaPlayer().create();
this.player.initialize(this.video_el, this.model.url, this.model.is_playing);
}
play_listener(){
if (this.model.is_playing){
this.player.play()
}
else {
this.player.pause()
}
}
connect_signals(): void {
this.connect(this.model.properties.is_playing.change, this.play_listener);
this.connect(this.model.properties.time.change, ()=>this.player.seek(this.model.time));
}
}
export namespace DashViewer {
export type Attrs = p.AttrsOf<Props>
export type Props = Div.Props & {
video_element_id: p.Property<string>
url: p.Property<string>
is_playing: p.Property<boolean>
time: p.Property<number>
}
}
export interface DashViewer extends DashViewer.Attrs {}
export class DashViewer extends Div {
properties: DashViewer.Props
__view_type__: DashViewerView
constructor(attrs?: Partial<DashViewer.Attrs>) {
super(attrs)
}
static init_DashViewer(): void {
this.prototype.default_view = DashViewerView
this.define<DashViewer.Props>({
video_element_id: [p.String, 'dashviewer_video'],
url: [p.String, ''],
is_playing: [p.Boolean, false],
time: [p.Number, 0.0]
})
}
}
"""
class DashViewer(Div):
__implementation__ = JS_CODE
__javascript__ = [DASH_URL]
__css__ = []
video_element_id = String(default='dash_player', help="id of the video element in the DOM")
url = String(help="The URL from which to load the video. (This should point to an mpd file.)")
is_playing = Bool(default=False)
time = Float(default=0.0, help="Time in seconds. Change this to make the player jump to that time.")
and_ is not working
can anyone help me out. i am new to flask
test.py
from flask import session,Flask,render_template,request
from models import *
import os
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
#app.route('/')
def index():
query= book.query.filter(and_ (book.title=='we all lost',book.publication_year==2050)).all()
for i in query:
print(i.title)
return render_template('hellotesting.html',m=query)
hellotesting.html
<html>
<head></head>
<body>
<ol>
<li>{{m.title}} </li>
<li>{{m.author}} </li>
<li>{{m.publication_year}}</li>
</ol>
</body>
</html>
error
NameError
NameError: name 'and_' is not defined
i dont know why it is not working
You need to import it before you can use it
from sqlalchemy import and_
and then
query = book.query.filter(and_(book.title=='we all lost',book.publication_year==2050)).all()
Also in your hellotesting.html file you try to display attribute of queryset (something like list of your model instances), not particular object and it will raise exception. You have to get any object from queryset in function or in template before call it's attribute.
In function you can do something like
query = book.query.filter(and_(book.title=='we all lost',book.publication_year==2050)).first()
or
book = query[0]
and then put that object to render_template function or you can do something similar in template like
{{ m[0].title }}
Read documentation for more examples and explenations
I try to post an image to process it through my REST API. I use falcon for the backend but could not figure out how to post and receive the data.
This is how I currently send my file
img = open('img.png', 'rb')
r = requests.post("http://localhost:8000/rec",
files={'file':img},
data = {'apikey' : 'bla'})
However at the Falcon repo they say that Falcon does not support HTML forms to send data instead it aims full scope of POSTed and PUTed data which I do not differentiate POSTed image data and the one sent as above.
So eventually, I like to learn what is the right workaround to send a image and receive it by a REST API which is supposedly written by Falcon. Could you give some pointers?
For this you can use the following approach:
Falcon API Code:
import falcon
import base64
import json
app = falcon.API()
app.add_route("/rec/", GetImage())
class GetImage:
def on_post(self, req, res):
json_data = json.loads(req.stream.read().decode('utf8'))
image_url = json_data['image_name']
base64encoded_image = json_data['image_data']
with open(image_url, "wb") as fh:
fh.write(base64.b64decode(base64encoded_image))
res.status = falcon.HTTP_203
res.body = json.dumps({'status': 1, 'message': 'success'})
For API call:
import requests
import base64
with open("yourfile.png", "rb") as image_file:
encoded_image = base64.b64encode(image_file.read())
r = requests.post("http://localhost:8000/rec/",
data={'image_name':'yourfile.png',
'image_data':encoded_image
}
)
print(r.status_code, r.reason)
I hope this will help.