Re: [Tutor] Error when trying to insert csv values into a sql table

2019-06-11 Thread Peter Otten
Cravan wrote:

> Here is the stack overflow link:
> https://stackoverflow.com/questions/56540292/error-when-trying-to-insert-csv-values-into-a-sql-table
> 
>  
> 
> I'm getting a weird error code when I try to store values from a csv into
> an sql table in a movie review assignment.

Like they say on stackoverflow: it very much looks like the movies table 
doesn't exist. Maybe you have forgotton a commit somewhere?

Please double-check that the table is actually created before you look for 
other less likely causes of your problem.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error when trying to insert csv values into a sql table

2019-06-11 Thread Cravan
Here is the stack overflow link: 
https://stackoverflow.com/questions/56540292/error-when-trying-to-insert-csv-values-into-a-sql-table

 

I'm getting a weird error code when I try to store values from a csv into an 
sql table in a movie review assignment.

I have already edited my apostrophes and spacing and looked up examples from 
google to try and resolve my error to no avail. I also ensured that i defined 
DATABASE_URL properly. Sorry for the long traceback error at the end :P Please 
note that my csv values are stored in lists in each cell. They are arranged in 
a single column such as

The Lego Movie;2014;100;tt1490017;7.8

This is my main code

import os

from sqlalchemy import create_engine

from sqlalchemy.orm import scoped_session, sessionmaker

 

engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from 
SQLAlchemy that manages connections to the database

  # DATABASE_URL is an 
environment variable that indicates where the database lives

 

db = scoped_session(sessionmaker(bind=engine)) 

def main():

    f = open("movies.csv","r")

    reader = csv.reader(f)

    for row in f: # loop gives each column a name

    vals = row.split(';')

    title = vals[0]

    year = vals[1]

    runtime = vals[2]

    imdbID = vals[3]

    imdbRating = vals[4]

    db.execute('INSERT INTO movies (Title, Year, Runtime, imdbID, 
imdbRating) VALUES (:title, :year, :runtime, :imdbID, :imdbRating)',

  {'title': title, 'year': year, 'runtime': runtime, 
'imdbID': imdbID, 'imdbRating': imdbRating}) # substitute values from CSV line 
into SQL command, as per this dict

    print(f"Added movie named {title} of {year} lasting {runtime} minutes. 
Its imdbID is {imdbID} and its imdbRating is {imdbRating}.")

This is the sql

CREATE TABLE movies (

  Title SERIAL PRIMARY KEY,

  Year INTEGER NOT NULL,

  Runtime INTEGER NOT NULL

  imdbID VARCHAR NOT NULL,

  imdbRating INTEGER NOT NULL

  );

This is the error i got:

Traceback (most recent call last):

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1244, in _execute_context

    cursor, statement, parameters, context

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/default.py", line 550, in do_execute

    cursor.execute(statement, parameters)

psycopg2.errors.UndefinedTable: relation "movies" does not exist

LINE 1: INSERT INTO movies (Title, Year, Runtime, imdbID, imdbRating...

The above exception was the direct cause of the following exception:

 

Traceback (most recent call last):

  File "import.py", line 25, in 

    main()

  File "import.py", line 21, in main

    {'title': title, 'year': year, 'runtime': runtime, 'imdbID': imdbID, 
'imdbRating': imd

bRating}) # substitute values from CSV line into SQL command, as per this dict

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/orm/scoping.py", line 162, in do

    return getattr(self.registry(), name)(*args, **kwargs)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/orm/session.py", line 1268, in execute

    clause, params or {}

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/orm/session.py", line 1268, in execute

    clause, params or {}

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 988, in execute

    return meth(self, multiparams, params)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/sql/elements.py", line 287, in _execute_on_connection

    return connection._execute_clauseelement(self, multiparams, params)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1107, in _execute_clauseelement

    distilled_params,

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1248, in _execute_context

e, statement, parameters, cursor, context

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/engine/base.py", line 1466, in _handle_dbapi_exception

    util.raise_from_cause(sqlalchemy_exception, exc_info)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/util/compat.py", line 383, in raise_from_cause

    reraise(type(exception), exception, tb=exc_tb, cause=cause)

  File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqla

lchemy/util/compat.py", line 128, in reraise

    raise value.with_traceback(tb)

  File 

[Tutor] Broadcasting using sockets over adhoc wifi

2019-06-11 Thread John Hoeksema
Hello!

Summer researcher using Raspbian and Python 3.5.

I'm trying to use a Raspberry Pi 3 B+ to broadcast a message using the
sockets library to other Pis (same model) over their shared ad-hoc network.
All of the Pis can ping the others over the ad hoc network. The Pis can
also communicate using pretty standard client-server code and the python
socket library . However,
when I try to *broadcast* a message, the Pis give a "Network is
unreachable" message (full error down below). A grad student I'm working
with said that the script he provided me expects the server to be run in
infrastructure mode, and configuration for ad-hoc mode is required to make
it work correctly. This is confirmed, as I have successfully run the code
on a desktop. I have poured over man pages and stackoverflow, and can't
seem to find resources for how to configure socket broadcasts for ad-hoc
networks. Any thoughts?

The function is supposed to broadcast a message to a specific port after
every [frequency] seconds, and any machines on the same network and
connected to the same port should receive the message. The function is the
only method of the *Server* class.

*Broadcast function:*
def broadcast(self, frequency, port):

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server.settimeout(0.2)

while True:
server.sendto("GET OUT OF MY SWAMP", ('', port))
print("message sent...")
time.sleep(frequency)

*Error message:*
Traceback (most recent call last):
  File "myServer.py", line 31, in 
s.broadcast(float(frequency),int(port))
  File "myServer.py", line 22, in broadcast
server.sendto("GET OUT OF MY SWAMP", ('', port))
socket.error: [Errno 101] Network is unreachable

Thank you for your time. Please let me know any information you think would
be useful!

Best,
John

-- 
*John Hoeksema*
Computer Science
University of Notre Dame '21
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python printing parentheses and quotes

2019-06-11 Thread Sai Allu
Thank you Cameron,

This was something that I was working on last week and I've been able to fix 
the script since then. I was just curious why the previous version did that and 
you might be right, thank you for the help though!

Best Wishes,
Sai Allu

From: Cameron Simpson 
Sent: Monday, June 10, 2019 5:34 PM
To: Sai Allu
Cc: Mats Wichmann; tutor@python.org; Deepak Dixit
Subject: Re: [Tutor] Python printing parentheses and quotes

On 10Jun2019 19:04, Sai Allu  wrote:
>Actually I'm pretty sure what happened was that the "#! usr/bin/python" was in 
>a module that was being imported. So the Python interpreter cached it or 
>somehow crashed randomly, which meant that the print was working as a keyword 
>instead of a function.
>
>But when I removed that "#! usr/bin/python" line and then rewrote the print 
>statements, it went back to working normally.

My personal suspicision is that what you might have been doing is this
(notice the trailing comma):

  print("",)

or maybe:

  print("this", that")

Look:

  % python
  Python 2.7.16 (default, Apr  1 2019, 15:01:04)
  [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> print("",)
  ('',)
  >>>

  % python3
  Python 3.7.3 (default, Mar 30 2019, 03:38:02)
  [Clang 8.0.0 (clang-800.0.42.1)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> print("",)

  >>>

What is happening?

In Python 2, print is a statement unless you use the __future__ import
already mentioned. That means that this:

  print("",)

is a "print" of the expression ("",), which is a 1-tuple, and gets
printed as a tuple. The more likely scenario is when you're printing
mulitple things:

  print("this", "that")

which is still a "print" of a tuple.

However, in Python 3 print is a function which means that the brackets
are part of the function call. So this:

  print("")

or:

  print("this", "that")

is a call to the "print()" function, passing one or two arguments, which
get printed. And printing "" (the former case) is an empty string.

Please revisit your code can test this.

Subtle issues like this are why we like to receive _exact_ cut/paste of
your code and the matching output, not a retype of what you thought you
ran. If you encounter something weird like this, it is well worth your
time (and ours) if you make a tiny standalone script showing the
problem, as small as possible. Then paste it into your message and paste
in the output (this list drops attachments). That we we can all run
exactly the same code, and solve your actual problem.

And start always using:

  from __future__ import print_function

in Python if you're using print. That will make your prints behave the
same regardless if whether they are using Python 2 or 3.

Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor