I want to send a http GET request using QWebEngineHttpRequest.
I know it is possible, as I found this question with a POST request using it.
So, I've ended up with some code but it doesn't work. Let's say I want to make a get request to facebook webpage and print the answer, which should be the HTML content of the page.
import sys
from PyQt5 import *
def handle_response():
print(bytes(replyObject.readAll()).decode("utf-8"))
if __name__ == "__main__":
def app():
app = QApplication(sys.argv)
req = QtWebEngineCore.QWebEngineHttpRequest(QUrl("https://stackoverflow.com/questions/51686198/",
method=QWebEngineHttpRequest.Get)
req.setHeader(QByteArray(b'Content-Type'),QByteArray(b'application/json'))
web = QWebEngineView()
web.loadFinished.connect(on_load_finished) # will be error
sys.exit(app.exec_())
Ok, I found how to make this:
import sys
from PyQt5.QtCore import QByteArray, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineCore import QWebEngineHttpRequest
from PyQt5.QtWebEngineWidgets import QWebEnginePage
class Render(QWebEnginePage):
def __init__(self, url):
app = QApplication(sys.argv)
QWebEnginePage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self._html = ""
username = "username"
password = "password"
base64string = QByteArray(("%s:%s" % (username, password)).encode()).toBase64()
request = QWebEngineHttpRequest(QUrl.fromUserInput(url))
equest.setHeader(b"Authorization", b"Basic: %s" % (base64string,))
self.load(request)
app.exec_()
#property
def html(self):
return self._html
def _loadFinished(self):
self.toHtml(self.handle_to_html)
def handle_to_html(self, html):
self._html = html
QApplication.quit()
def main():
url = "http://www.google.com"
r = Render(url)
print(r.html)
if __name__ == "__main__":
main()
Thanks to link
Related
from flask import Flask, request
from flask_restplus import Resource, Api
app = Flask(name)
api = Api(app)
todos = {}
#api.route('/string:todo_id')
class TodoSimple(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]}
def put(self, todo_id):
todos[todo_id] = request.form['data']
return {todo_id: todos[todo_id]}
if name == 'main':
app.run(debug=True)
I am trying to add multiple inner function in my code. But I am not able to add it properly and also it is giving me a syntax error. Here I am trying to run my python script when I click a button and it will take input from a textfield and then run my script which has multiple functions. Is this the right way to add inner functions or is there another way to do this?
ERROR
File "server.py", line 17``
pass = request.form['typed']here
^
SyntaxError: invalid syntax
[1]: https://i.stack.imgur.com/H6Mg2.png
from flask import Flask, render_template, url_for, request, redirect
app= Flask(__name__)
#app.route('/')`enter code here`
def my_home():
return render_template('index.html')
#app.route('/<string:page_name>')
def html_page(page_name):
return render_template(page_name)
import hashlib
import sys
import requests
#app.route('/send',methods =['POST'])
def send():
if request.method == 'POST':
pass = request.form['typed']
def request_api_data(query_char)
res = requests.get(url)
if res.status_code != 200:
raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again')
return res
pass is a statement and cannot be used as a variable name.
https://docs.python.org/3/tutorial/controlflow.html#pass-statements
from flask import Flask, render_template, url_for, request, redirect
app= Flask(__name__)
#app.route('/')`enter code here`
def my_home():
return render_template('index.html')
#app.route('/<string:page_name>')
def html_page(page_name):
return render_template(page_name)
import hashlib
import sys
import requests
#app.route('/send',methods =['POST'])
def send():
if request.method == 'POST':
# pass = request.form['typed']
my_pass = request.form['typed'] # <- this should work.
def request_api_data(query_char)
res = requests.get(url)
if res.status_code != 200:
raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again')
return res
First of all, I have tried looking for answers in this website. But no luck...
What I wanna achieve is that starting an independent thread in the request handling thread to do some asynchronous task. The tricky point is that there are some database operations needed in this independent thread.
Here is an example. Five files included.
project
|__manager.py
|__config.py
|__deployer
|__`__init__.py`
|__models.py
|__views.py
|__operators.py
Detail code below...
# deployer/__init__.py
from flask import Flask
from deployer.models import db
def create_app():
app = Flask(__name__)
app.config.from_object(object_name)
db.init_app(app)
# Add route for index
#app.route('/')
def index():
return {'code': 200, 'message': 'OK'}
return app
# manager.py
from os import environ
from flask_script import Manager, Server
from deployer import create_app
from flask_restful import Api
from deployer.views import HostView
env = environ.get('APM_ENV', 'dev')
app = create_app('config.%sConfig' % env.capitalize())
api = Api(app)
api.add_resource(HostView, '/api/v1/hosts')
manager = Manager(app)
manager.add_command("server", Server(host='0.0.0.0', port=9527))
if __name__ == '__main__':
manager.run(default_command='server')
# deployer/views.py
from flask_restful import Resource, reqparse
from flask import jsonify
from deployer.models import db, Host
from deployer.operators import HostInitiator
parser = reqparse.RequestParser()
parser.add_argument('host', type=int, help='Specify an unique host.')
class HostView(Resource):
def get(self):
h = db.session.query(Host).filter(Host.id == 1).one()
return jsonify(
host_id=h.id,
host_code=h.code,
host_ip=h.ip_addr_v4
)
def post(self):
h = Host(
code='Harbor',
ip_addr_v4='10.10.10.199',
state='created'
)
db.session.add(h)
db.session.commit()
initiator = HostInitiator(host=h)
initiator.start()
return {
'code': 'Harbor',
'ip_addr_v4': '10.10.10.199',
'state': 'created'
}
# deployer/models.py
from sqlalchemy import Column, Integer, String
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Host(db.Model):
__tablename__ = 'br_host'
id = Column(Integer, primary_key=True, autoincrement=True)
code = Column(String(128), index=True, nullable=False)
ip_addr_v4 = Column(String(15), nullable=False)
state = Column(String(16), nullable=False)
# deployer/operators.py
from threading import Thread
from deployer.models import db
class HostInitiator(Thread):
def __init__(self, host):
super().__init__()
self.host = host
def run(self):
# Update Host.state [created-->initating]
db.session.query(Host).filter(Host.id == self.host.id).update({'state': 'initating'})
db.session.commit()
# do some initiating things...
# Update Host.state [initating-->ready]
db.session.query(Host).filter(Host.id == self.host.id).update({'state': 'ready'})
db.session.commit()
Always got outside application context error with code above. The error message indicates that no database operation is permitted in the HostInitiator thread.
It suggests me to push a context or move my code into a view function. I'm suffering this quite a while, please help out if you guys have any suggestions. Thanks in advance.
The code works for me
def test_multi_threading_query():
# module which i create Flask app instance
from app.main import app
# module which i create sqlalchemhy instance
from app.model.db import db, Post
with app.app_context():
posts = Post.query.all()
p = posts[0]
p.foo = 1
db.session.add(p)
db.session.commit()
print(p)
#api.route('/test')
def test_view():
from threading import Thread
t = Thread(target=test_multi_threading_query)
t.start()
return ''
# main.py
app = Flask(__main__)
#db.py
db = SQLAlchemy()
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
foo = db.Column(db.Integer)
https://flask.palletsprojects.com/en/1.1.x/appcontext/
I wanted to post and update data in yaml file through tornado api call .. could you please give some code example
import tornado.web
import tornado.ioloop
import nest_asyncio
import json
class basicRequestHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello , world...." )
if __name__ =="__main__":
app = tornado.web.Application([(r"/", basicRequestHandler)])
app.listen(8881)
print("I'm listening on port 8881")
tornado.ioloop.IOLoop.current().start()
Prepared for you this example:
from typing import Dict
import tornado.web
import tornado.ioloop
import yaml
from tornado.escape import json_decode
class BaseHandler(tornado.web.RequestHandler):
yaml_filename = 'data.yaml'
json_args: Dict
async def prepare(self):
self.json_args = json_decode(self.request.body) or {}
def data_received(self, chunk):
...
class MainHandler(BaseHandler):
def post(self):
with open(self.yaml_filename, 'w') as file:
# ...
yaml.dump(self.json_args, file)
def put(self):
with open(self.yaml_filename) as file:
yaml_data = yaml.full_load(file)
# ...
yaml_data.update(self.json_args)
# ...
with open(self.yaml_filename, 'w') as file:
yaml.dump(yaml_data, file)
if __name__ == "__main__":
app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8881)
print("I'm listening on port 8881")
tornado.ioloop.IOLoop.current().start()
My Python Flask App is unable to decode the devanagari text eg:"सिंगापूर" that I pass as urlparam from my postman. If I sen english text it handles it well.
My PostMan query :
GET http://localhost:5000/getSimilarWord/सिंगापूर
from flask import Flask
from flask_restful import Resource, Api
class DevnagriText(Resource):
def get(self, textInput):
print("parsed String is :",textInput)
return {'text': textInput}
api.add_resource(DevnagriText, '/getWord/<string:textInput>')
if __name__ == '__main__':
app.run(debug=True)
The output I get on console is
{
"text": "\u00818"
}
Instead of
{
"text": "सिंगापूर"
}
You need to prevent the response from forcing ASCII: app.config['JSON_AS_ASCII'] = False
So in your example:
from flask import jsonify, Flask
from flask_restful import Resource, Api
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
api = Api(app)
class DevnagriText(Resource):
def get(self, textInput):
print("parsed String is :",textInput)
return jsonify(text=textInput)
api.add_resource(DevnagriText, '/getWord/<string:textInput>')
if __name__ == '__main__':
app.run(debug=True)
But, this doesn't really matter, it will all get interpreted the same way if it gets read into Python or JavaScript.