I tried flask Python Splinter but is is not working? - python-3.x

I was trying splinter as an alternative of selenium but it's not working correctly.
Traceback (most recent call last):
File "C:\scrapper.py", line 14, in <module>
browser = Browser('flask', app=app)
File "C:\.env\lib\site-packages\splinter\browser.py", line 121, in Browser
return get_driver(driver, retry_count=retry_count, *args, **kwargs)
File "C:.env\lib\site-packages\splinter\browser.py", line 92, in get_driver
return driver(*args, **kwargs)
TypeError: 'NoneType' object is not callable
my program
from flask import Flask
app = Flask(__name__)
#app.route('/')
def main():
return 'Hello, World!'
#app.route('/<name>')
def hello_world(name):
return 'Hello, {name}!'.format(name=name)
# initiate splinter flask client
from splinter import Browser
browser = Browser('flask', app=app)
print(browser.html)

Related

Python script doesn't recognize 'self' argument in PyQt MainWindow

I'm trying to get a PyQt lineEdit widget to place its' contents within a variable in the module 'followup' but for some reason the module does not recognize the PyQt MainWindow as being properly instantiated.
#workbot_main.py
import gspread
import os
import sys
sys.path.append(os.path.abspath(r"C:\Users\leamy\Desktop\work bot\workbot.py"))
sys.path.append(os.path.abspath(r"C:\Users\leamy\Desktop\work bot\initial.py"))
sys.path.append(os.path.abspath(r"C:\Users\leamy\Desktop\work bot\followup.py"))
import threading
import followup
import initial
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow, QApplication
from workbot import *
import workbot
#workbot.py is the QTdesigner file containing the widgets,
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
followup_start_button = self.ui.followup_start_button
followup_start_button.clicked.connect(threads.begin_initialize)
def followup_starting_number(self):
num = self.ui.lineEdit.text()
return num
def begin_initialize(self):
t1 = threading.Thread(target = followup.initialize, args = ())
t1.start()
threads = Threads()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
widget = MainWindow()
widget.show()
app.exec_()
#followup.py
import workbot_main
def initialize():
row_number.number = workbot_main.MainWindow.followup_starting_number()
print(row_number.number)
I get this error
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\leamy\anaconda3\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\leamy\anaconda3\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\leamy\Desktop\work bot\followup.py", line 313, in initialize
row_number.number = workbot_main.MainWindow.followup_starting_number()
TypeError: followup_starting_number() missing 1 required positional argument: 'self'
I can't understand why it doesn't work.
Edit:
If I try to use
row_number.number = workbot_main.widget.followup_starting_number()
instead of
row_number.number = workbot_main.MainWindow.followup_starting_number()
I get this error
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\leamy\anaconda3\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\leamy\anaconda3\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\leamy\Desktop\work bot\followup.py", line 314, in initialize
row_number.number = workbot_main.widget.followup_starting_number()
AttributeError: module 'workbot_main' has no attribute 'widget'
I don't know if that is related.

Threading Class - 'int' not iterable | Flask

I'm current encountering an issue where I'm using threads to perform tasks in the background upon a POST request, but I'm having an issue with using an integer as a parameter; or any data type as a parameter for that matter.
What is supposed to happen is that it's supposed to perform everything inside of the POST request check, then perform something else after that has been completed.
Imports:
from flask import Flask, url_for, render_template, redirect, request
from flask.cli import with_appcontext, click
import sqlalchemy
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, login_required, current_user
Thread Class:
#click.command(name='run')
#click.pass_context
class Compute(Thread):
def __init__(self, secs):
Thread.__init__(self)
self.secs = secs
def run(self):
print('Thread Opened')
sleep(self.secs)
db.session.query(Users).filter(Users.username == current_user.username).first().requests += 1
db.session.commit()
print('Thread Closed')
Flask Route:
#app.route('/index', methods=['GET', 'POST'])
#login_required
def index():
if request.method == 'POST':
time = '5'
thread = Compute(int(time))
thread.start()
return redirect(url_for('index'))
else:
return render_template('index.html')
The error I am receiving when the thread tries to start is this:
Traceback (most recent call last):
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e)
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb)
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request()
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\flask_login\utils.py", line 272, in decorated_view return func(*args, **kwargs)
File "c:/Users/myuser/Desktop/Projects/Python/app.py", line 104, in layer4
thread = Compute(int(time))
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\click\core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\click\core.py", line 767, in main
args = list(args)
TypeError: 'int' object is not iterable
I am not very experienced with threading, I've only dabbled with it in other projects so I'm not sure why I'm getting this error; any help is greatly appreciated.
You need to remove the #click.command and #click.pass_context decorators.
#click.command(name='run')
#click.pass_context
class Compute(Thread):
Those decorators are wrapping the class in a function that takes its own parameters. It is intended for running a function from the command line and parsing arguments. This is why the traceback shows args = list(args) as the line causing the error.
https://github.com/pallets/click/blob/master/src/click/core.py#L916-L917
:param args: the arguments that should be used for parsing. If not
provided, ``sys.argv[1:]`` is used.

No current context error after Python 3 migration, should I include more logic?

I'm converting a Google App Engine Python 2 project to Python 3
My understanding from reading the documentation I understand the preferred path is to run the main python program directly, skipping dev_appserver.py as was done in the past.
https://cloud.google.com/appengine/docs/standard/python3/tools/local-devserver-command
python3 main.py
--- main.py --
# coding: utf-8
import flask
from flask import request, redirect, url_for
from flask_basicauth import BasicAuth
#from urllib# import urlparse, urlunparse
import config
--- config.py
import model
...
33: CONFIG_DB = model.Config.get_master_db()
--- model/config.py
from __future__ import absolute_import
from google.cloud import ndb
#from oauth2client.contrib.appengine import CredentialsNDBProperty
from api import fields
import config
import model
import util
...
class Config(model.Base, model.ConfigAuth):
...
#classmethod
def get_master_db(cls):
57: return cls.get_or_insert('master')
When running the following trace is prod
Traceback (most recent call last):
File "main.py", line 9, in <module>
import config
File "/home/ffej/cloudpayback/main/config.py", line 33, in <module>
CONFIG_DB = model.Config.get_master_db()
File "/home/ffej/cloudpayback/main/model/config.py", line 57, in get_master_db
return cls.get_or_insert('master')
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/utils.py", line 146, in positional_wrapper
return wrapped(*args, **kwds)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/model.py", line 5698, in _get_or_insert
return cls._get_or_insert_async(
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/utils.py", line 146, in positional_wrapper
return wrapped(*args, **kwds)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/model.py", line 5811, in _get_or_insert_async
key = key_module.Key(cls._get_kind(), name, parent=parent, **key_args)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/key.py", line 290, in __new__
context = context_module.get_context()
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/context.py", line 96, in get_context
raise exceptions.ContextError()
google.cloud.ndb.exceptions.ContextError: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context.
Is there additional logic that should be included after migration to start/initialize the datastore?
Thanks,
Jeff
The API for NDB library in Python3 has changed significantly. For developing on localhost you have to:
run DataStore Emulator, since you're not running dev_appserver anymore:
$ gcloud beta emulators datastore start
if you use the new NDB Library, then each NDB operation needs to be wrapped in a context manager:
with ndb_client.context(): # <- you need this line
cls.get_or_insert('master')
edit: instead of wrapping each NDB call with a context manager, you can use a middleware which will wrap the whole request cycle into the NDB context:
class NDBMiddleware:
def __init__(self, app):
self.app = app
self.client = ndb_client
def __call__(self, environ, start_response):
with self.client.context():
return self.app(environ, start_response)
app = Flask(__name__)
app.wsgi_app = NDBMiddleware(app.wsgi_app)

Why is variable showing up as undefined?

I am using flask to create a webform on http://localhost:5000/ and my goal is for the form to prompt the user for two inputs, then write those inputs into two new python3 files named test2.py and test3.py. The variable 'text' and 'text1' keep coming up as undefined. Here is the code and its error:
code:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('my-form.html')
#app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
text1 = request.form['text1']
with open('test2.py', 'w+') as file:
file.write(text)
with open('test3.py', 'w+') as file:
file.write(text1)
error:
Traceback (most recent call last):
File "test1.py", line 15, in <module>
file.write(text)
NameError: name 'text' is not defined
Thanks!
That is because text and text1 are defined in the function, while file handling is outside. The file handling should be inside the post method.

Selenium Testing in Firefox under session id

E
======================================================================
ERROR: test_LoginCorrect (__main__.LoginCorrect)
----------------------------------------------------------------------
Traceback (most recent call last):
File "demo.py", line 12, in test_LoginCorrect
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 248, in
start_session
self.session_id = response['sessionId']
TypeError: string indices must be integers
----------------------------------------------------------------------
Ran 1 test in 20.878s
//Formatting is not properly done
FAILED (errors=1)
My test case file :
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class LoginCorrect(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Remote(command_executor='http://0.0.0.0:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX)
def test_LoginCorrect(self):
user ="shubh"
pwd= "sha123#56su"
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
driver.get("http://0.0.0.0:8000/login")
elem = driver.find_element_by_id("id_username")
elem.send_keys(user)
elem = driver.find_element_by_id("id_password")
elem.send_keys(pwd)
driver.find_element_by_class_name('btn-block').click()
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
My machine has Linux 16.04LTS and selenium 3.3.0
Can somebody figure out this problem.

Resources