Why is variable showing up as undefined? - python-3.x

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.

Related

I tried flask Python Splinter but is is not working?

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)

Calling a Python File from another file and viceversa

I have few common functions written in file a.py which is called from file b.py. And, also I have few common functions written in file b.py which is called from file a.py. but when I try to run these files I get error as unable to import name. Below is the code for reference.
I have just provided an example below, these files have common piece of code in real scenario which is specific to a functionality and that is the reason its being called from one another
a.py code below
from b import get_partner_id
def get_customer_id(tenant_id):
customer_id = tenant_id + "tenant_name"
return customer_id
def get_partner_details():
partnerid = get_partner_id()
data = {"partnerId": partnerid}
print(data)
b.py code below
from a import get_customer_id
def get_partner_id():
customer_id = get_customer_id("7687")
env = 'sandbox-all' + customer_id
return env
get_partner_id()
Below is the error for reference,
Traceback (most recent call last):
File "C:/testCases/b.py", line 1, in <module>
from a import get_customer_id
File "C:\testCases\a.py", line 2, in <module>
from b import get_partner_id
File "C:\testCases\b.py", line 1, in <module>
from a import get_customer_id
ImportError: cannot import name 'get_customer_id'

SQLAlchemy 1.2 AttributeError: 'list' object has no attribute 'Session'

I was trying to use the code snippet from this tutorial:
http://newcoder.io/scrape/part-4/
The following is the file with the class definition:
from sqlalchemy.orm import sessionmaker
from .models import Deals, db_connect, create_deals_table
class Test(object):
def __init__(self, args):
"""
Initializes database connection and sessionmaker.
Creates deals table.
"""
engine = db_connect()
create_deals_table(engine)
self.Session = sessionmaker(bind=engine)
def add_item(self):
session = self.Session()
tester = Deals(title="test 3 deal",location='here', price=2.00)
session.add(tester)
session.commit()
When I call Test.add_item(args), the following error is generated.
(sql) [bucket#localhost heap]$ python heap.py test Traceback (most
recent call last): File "heap.py", line 13, in <module>
main(sys.argv) File "heap.py", line 8, in main
Test.add_item(args) File "/home/bucket/src/heap/game/engine.py", line 17, in add_item
session = self.Session() AttributeError: 'list' object has no attribute 'Session'
The code worked fine and added a row when I ran the the same code as a python script with no class definition.
You're trying to call an instance method on the class itself: Test.add_item(args)
You define the method as only having self and no parameters. This means that you need to call it on an instance of the class, and pass it no arguments
test = Test()
test.add_item()
The reason you're getting that particular error is because you're calling the function with the list argument args getting used as the parameter self, and then the self.Session() line is attempting to get the attribute Session from the args object. You need to fix either the method definition or your call to it (e.g., def add_item(self, args):)

ImportError: No module named url

when i run the the given code in prepare_dataset.py whose code is below as
from urllib.request
import urlopen
import json as simplejson
def main():
# Download and prepare datasets
list_generator = video_list_generator.Generator("playlists.json", youtube_api_client.Client("AIzaSyD_UC-FpXbJeWzPfscLz9RhqSjKwj33q6A"))
video_list = list_generator.get_video_list("piano")
downloader = youtube_video_downloader.Downloader()
downloader.download_from_list(video_list)
if __name__ == '__main__':
main()
as python prepare_dataset.py in command-line then i get these errors
Traceback (most recent call last):
File "prepare_dataset.py", line 1, in <module>
from urllib.request import urlopen
ImportError: No module named request
How can i get to run the above file any idea guys?

AttributeError: 'module' object has no attribute 'urlretrieve'

I am trying to write a program that will download mp3's off of a website then join them together but whenever I try to download the files I get this error:
Traceback (most recent call last):
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 214, in <module> main()
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 209, in main getMp3s()
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 134, in getMp3s
raw_mp3.add = urllib.urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
AttributeError: 'module' object has no attribute 'urlretrieve'
The line that is causing this problem is
raw_mp3.add = urllib.urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve saves the file to a temporary file and returns a tuple (filename, headers)
urlopen returns a Request object whose read method returns a bytestring containing the file contents
A Python 2+3 compatible solution is:
import sys
if sys.version_info[0] >= 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlretrieve
# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

Resources