Juan Christian | 22 Sep 22:30 2014
Picon

Re: Python advice about API, JSON

On Mon, Sep 22, 2014 at 5:10 PM, Patrick Thunstrom <pathunstrom <at> gmail.com> wrote:
On Mon, Sep 22, 2014 at 4:01 PM, Juan Christian
<juan0christian <at> gmail.com> wrote:
> I'm trying to make my script the more pythonic possible. How would a good
> approach regarding external API and json be?

I don't think dealing with a specific API is actually appropriate for
this list. I'll try to answer the general elements.

But I do want the "general" approach, I just talked about the API I'm using for the sake of example.

I don't need multiple versions of the class API, I would have only one. I would need multiple instances, because I have a person class, movie class and serie class, and each of them would need their API obj.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Juan Christian | 22 Sep 22:01 2014
Picon

Python advice about API, JSON

I'm trying to make my script the more pythonic possible. How would a good approach regarding external API and json be?

I'm calling this API (http://docs.themoviedb.apiary.io/) using 'requests'. The thing is that I need to do a bunch of different calls to the API:

http://api.themoviedb.org/3/person << Receive ID and return person info
http://api.themoviedb.org/3/tv << Receive ID and return serie info
http://api.themoviedb.org/3/movie << Receive ID and return movie info
http://api.themoviedb.org/3/search << Receive "Name of person or serie or movie" and return ID

I have the following structures: 

- {query}/{type}?api_key={key}&query={person or tv or movie}
- {query}/{id}?api_key={key}
- {query}/{id}/credits?api_key={key}
- {query}/{id}/season/{season_numer}?api_key={key}
- {query}/{id}/season/{season_numer}/episode/{episode_number}?api_key={key}
- {query}/{id}/season/{season_numer}/episode/{episode_number}/credits?api_key={key}


I'm thinking about creating a class 'API' and have all these URLs and structures there. The thing is that I need to pass my API_KEY and this key will be used for everything, so I just need to pass it once, how can I do that? Yes, I know about class attributes, but the thing is that I will call this class 'API' from different classes and I'll need to instantiate a API obj in each of them, is it a good approach? Inside this 'API' class I would have a __init__ that would receive an API_KEY and different methods, each for a type of query (person, tv, movie, search, credits).

Maybe my explanation is a bit confusing but I hope you guys understood, anyway, you can ask for more information if needed!

And another thing, What's better, a single module with multiple classes (total lines: ~110) or multiple modules with 1-3 classes (correlated, like class serie, season and episode in the same module, and class person and character in the same module) each?

Thanks!
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Danny Yoo | 22 Sep 00:30 2014

Fwd: question 1

Forwarding Clayton's original request to tutor:

---------- Forwarded message ----------
From: Clayton Kirkwood <crk <at> godblessthe.us>
Date: Sun, Sep 21, 2014 at 2:42 PM
Subject: RE: [Tutor] question 1
To: Danny Yoo <dyoo <at> hashcollision.org>

> Secondarily, why can you import a module without it importing all of
> its daughters?

The act of importing a module is "recursive": if you import a module,
and that module itself has import statements, then Python will do the
import of the child modules too.  And so forth.
> And why do you have to use a ‘for in to import submodule’, why not
> ’import module.sub’?

If I'm not mistaken, you _can_ do this.  Can you point us to a source
where it says you can't?

(There are particular style guidelines from certain organizations that
prohibit this kind of import, but that prohibition is by convention.
That is, it's not because the language disallows it, but because it
doesn't fit with the house coding style.)

[Clayton Kirkwood]
From the interpreter:

import io
import io.FileIO
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.ImportError: No module named 'io.FileIO'; 'io' is not a package
from io import FileIO
:end

> Lastly, in some tutorials and else-sourced docs certain lines have a
> ‘;’ at the end. This seems to be most often with ‘opens’ and ‘fopen’ kind of calls.

Huh.  Can you point to a reference?  Note that third-party
documentation (and official documentation!) might be buggy or weird.
:P  If you can point us to an example, maybe one of us can investigate
what's going on there.
[Clayton Kirkwood]

Example from ' http://www.tutorialspoint.com/python/python_files_io.htm'

#!/usr/bin/python

str = raw_input("Enter your input: ");
print "Received input is : ", str
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Danny Yoo | 22 Sep 00:29 2014

Fwd: question 1

Forwarding response to tutor; didn't realize it was only sent to me.

---------- Forwarded message ----------
From: Danny Yoo <dyoo <at> hashcollision.org>
Date: Sun, Sep 21, 2014 at 3:10 PM
Subject: Re: [Tutor] question 1
To: Clayton Kirkwood <crk <at> godblessthe.us>

On Sun, Sep 21, 2014 at 2:42 PM, Clayton Kirkwood <crk <at> godblessthe.us> wrote:
>> Secondarily, why can you import a module without it importing all of
>> its daughters?
>
> The act of importing a module is "recursive": if you import a module, and that module itself has import
statements, then Python will do the import of the child modules too.  And so forth.
>> And why do you have to use a ‘for in to import submodule’, why not
>> ’import module.sub’?
>
> If I'm not mistaken, you _can_ do this.  Can you point us to a source where it says you can't?
>
> (There are particular style guidelines from certain organizations that prohibit this kind of import,
but that prohibition is by convention.
> That is, it's not because the language disallows it, but because it doesn't fit with the house coding style.)
>
>
> [Clayton Kirkwood]
> From the interpreter:
>
> import io
> import io.FileIO
> Traceback (most recent call last):
>   File "<string>", line 1, in <fragment>
> builtins.ImportError: No module named 'io.FileIO'; 'io' is not a package

Hi Clayton,

Ah.  But 'FileIO' is not a module.  It's a value in the 'io' module.
We can see this here:

#######################################################
dhcp-9:work dyoo$ python
Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import io
>>> io
<module 'io' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.pyc'>
>>> io.FileIO
<type '_io.FileIO'>
#######################################################

When we say:

    import xxx

then the "xxx" has to be a module.

The 'from/import' statement is deceptively named, unfortunately; it's
doing a little more than just module import.

    https://docs.python.org/2/tutorial/modules.html#more-on-modules

where when we say:

   from xxx import yyy

then xxx.yyy could be a module, or it might not.  The act of module
import is involved, so in a sense, the statement is doing an import.
But the 'yyy' doesn't have to be a module.

When we say:

   from io import FileIO

we are taking a value from the 'io' module, and giving it the name 'FileIO

So yeah, it's a little confusing.  For that reason, certain style
guidelines have a say when something is appropriate to write, apart
from what Python technically allows.  As a concrete example, see:

    https://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Imports#Imports

Here, we see a style decision that is _more_ restrictive than what the
Python language allows.

> Huh.  Can you point to a reference?  Note that third-party documentation (and official documentation!)
might be buggy or weird.
> :P  If you can point us to an example, maybe one of us can investigate what's going on there.
> [Clayton Kirkwood]
>
>
> Example from ' http://www.tutorialspoint.com/python/python_files_io.htm'
>
> #!/usr/bin/python
>
> str = raw_input("Enter your input: ");
> print "Received input is : ", str

Just because something is on the web (or email) doesn't mean it's
correct or prefect.

:)

--

There are a few small problems with this example from tutorialspoint:

1.  The semicolon is superfluous.

Take it out: it will still work.

2.  The name 'str' is already a built-in,

    https://docs.python.org/2/library/functions.html#str

so the code here is shadowing the built-in.

In such a small test program, this is fine.  In a real program, I'd
ding this for readability issues.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Joel Goldstick | 21 Sep 21:21 2014
Picon

Re: Python 3: List Comprehensions + range

On Sun, Sep 21, 2014 at 2:36 PM, Juan Christian
<juan0christian <at> gmail.com> wrote:
> On Sun, Sep 21, 2014 at 3:28 PM, Joel Goldstick <joel.goldstick <at> gmail.com>
> wrote:
>>
>> You are calling Season with different parameters than it was defined to
>> accept.
>
>
> No, I'm not.
>
> Season > def __init__(self, ID, season, serie)
>
> and I'm calling it with Season(ID, season, self), I'm giving everything
> needed, don't I?

Shouldn't it be:  Season(ID, season, serie)?
>
> _______________________________________________
> Tutor maillist  -  Tutor <at> python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

--

-- 
Joel Goldstick
http://joelgoldstick.com
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Juan Christian | 21 Sep 16:18 2014
Picon

Python 3: List Comprehensions + range

I have a ' self.size = json['number_of_seasons'] ' that equals 5 (already checked), the problem is that the API have some series with special seasons, aka, season_number = 0, and I don't want to get those.

I have the following list comp: self.season = [Season(ID, season, self) for season in range(1, self.size + 1)]

Let's say I want Breaking Bad, 5 seasons, but this serie has a special season 0. Reading the list comp, I get a range from 1 (in order to ignore season 0) to 5 (range is half-open, so I need size + 1, maybe later I can implement a closed_range, but I don't think this will be necessary as this is the only place I'll ever use this). Then I get the current number and hold it on the var season, then I call Season() with this number, but I'm still fetching episodes from the season 0 and I don't know why!

Code:

import requests
from consts import API
from person import Person
from character import Character


class Serie:
def __init__(self, ID):
response = requests.get('{query}/{id}?api_key={key}'.format(query = API.QUERY_SERIE, id = ID, key = API.KEY))
json = response.json()

self.id = ID
self.title = json['name']
self.date = json['first_air_date']
self.size = json['number_of_seasons']
self.season = [Season(ID, season, self) for season in range(1, self.size + 1)]


class Season:
def __init__(self, ID, season, serie):
response = requests.get('{query}/{id}/season/{s}?api_key={key}'.format(query = API.QUERY_SERIE, id = ID, s = season, key = API.KEY))
json = response.json()

self.number = season
self.serie = serie
self.date = json['air_date']
self.episode = [Episode(ID, episode['episode_number'], self) for episode in json['episodes']]
self.size = len(self.episode)


class Episode:
def __init__(self, ID, episode, season):
response = requests.get('{query}/{id}/season/{s}/episode/{e}?api_key={key}'.format(query = API.QUERY_EPISODE, id = ID, s = season, e = episode, key = API.KEY))
json = response.json()
print(json)
print("\n")
self.number = episode
self.title = json['name']
self.date = json['air_date']

response = requests.get('{query}/{id}/season/{s}/episode/{e}/credits?api_key={key}'.format(query = API.QUERY_EPISODE, id = ID, s = season, e = episode, key = API.KEY))
json = response.json()

self.cast = [Character(person['character'], Person(person['id'])) for person in json['cast']]
self.cast_size = len(self.cast)


s = Serie("1396")
print("DEBUG: " + s.title + " : " + s.id + " : " + s.date + " : " + s.size)


print(json) is giving me:

{'vote_average': 0.0, 'id': 62131, 'air_date': '2009-02-17', 'still_path': '/t729tFVXPetnJlJ2VsUZQz0rX6v.jpg', 'overview
': "Hank and Marie try to spice up their relationship on Valentine's Day.", 'episode_number': 1, 'production_code': None
, 'season_number': 0, 'vote_count': 0, 'name': 'Good Cop Bad Cop'}


{'vote_average': 0.0, 'id': 62133, 'air_date': '2009-02-17', 'still_path': '/wT62P6ZnjKgZXk0M5hHl4e5zSjB.jpg', 'overview
': 'Walt and Hank have a talk before Hank gets married.', 'episode_number': 2, 'production_code': None, 'season_number':
 0, 'vote_count': 0, 'name': 'Wedding Day'}


{'vote_average': 0.0, 'id': 62132, 'air_date': '2009-02-17', 'still_path': '/gUHAqFw3Ptzya96JFFE9xVfMjze.jpg', 'overview
': 'Jesse and Badger make a behind the scenes video about their band "TwaughtHammer" and show a music video for their so
ng "Fallacies."', 'episode_number': 3, 'production_code': None, 'season_number': 0, 'vote_count': 0, 'name': 'TwaughtHam
mer'}

[...]

As you can see, 'season_number': 0, and I want 1 and above only.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Crush | 21 Sep 03:07 2014
Picon

Subprocess help

Hey all, hope everyone is well. 

I am trying to write a script that automates a certain task I have recently found myself doing a lot lately.

The command I need to run is "BYPASSROOT=yes ./octosetupBROADCASTER-linux_i386.bin"

I know how to use subprocess to execute the "./octosetup..." command, however the "BYPASSROOT=yes" is
stumping me seeing how it is not really a unix command. I assume it is changing a variable within
"octosetup...?" How do I get the "BYPASSROOT=yes" to be included in the subprocess.call? 

I know i know "root" is bad, but with this, I have no choice. 

Thanks 

Bo 
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Clayton Kirkwood | 21 Sep 00:20 2014
Picon

question 1

I’m ramping slowly unfortunately. How does one go about knowing which module to import to make certain functions work? I have a read() that fails because there is no definition for it. I am using the Wing IDE. I have traversed much of the developer’s guide and can’t find any certainty.

 

Secondarily, why can you import a module without it importing all of its daughters? And why do you have to use a ‘for in to import submodule’, why not ’ mport module.sub’?

 

Lastly, in some tutorials and else-sourced docs certain lines have a ‘;’ at the end. This seems to be most often with ‘opens’ and ‘fopen’ kind of calls.

 

Thanks,

 

Clayton

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Kate Reeher | 19 Sep 23:25 2014

making a list of a custom object

I have a custom class called Game, and it has a variable called "goals". I'd like to make this a list of custom objects, with various information about the goals.

class Game:
goals = {}
class Goal(object):
def __init__(self,time,goal_by,assist_by,team,is_powerplay ):
self.time=time
self.goal_by=goal_by
self.assist_by=assist_by
self.team=team
self.is_powerplay=is_powerplay


Is that Goal class set up correctly? 

For an instance of Game called game, is this how you'd set a variable of a goal?
game.goals[i].time= time 


I'm finding how python does data classes INCREDIBLY confusing, for whatever reason, so any help would be appreciated.

Thanks,
Kate

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Juan Christian | 20 Sep 01:00 2014
Picon

Converting timestamp read as str to "full date and time"

Let's say I have ' 1411167038 ' string that I got from an API and I need to convert it to something like ' Fri, 19 Sep 2014 22:50:38 GMT ' or maybe even the localtime of the PC.

I'm trying this way:

my_date = datetime.datetime.fromtimestamp(api['backpack_update'][GAME_ID]).strftime("%D %H:%M")

The key ' api['backpack_update'][GAME_ID] ' returns exactly what's expected, the timestamp in string format. But now I need to convert this to a "full date and time" so that I can print in the terminal/cmd like ' print(my_date) '.

I already read the https://docs.python.org/2/library/datetime.html and I think that the func 'strptime' may resolve my problem, already tried with this one, but didn't work.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Juan Christian | 19 Sep 19:30 2014
Picon

Using 'requests' + 'with statement' in Python 3.4.1

This part of my code isn't working:

def check_backpacktf(steamID64):
with requests.get(''.join([BACKPACKTF, steamID64])) as response:
status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': 'Private or invalid', 'steamrep_scammer': False}

with response.json()['response']['players'][steamID64] as api:
status['backpack_value'] = api['backpack_value'][GAME_ID]
status['steamrep_scammer'] = bool(api['steamrep_scammer'])

return status

-----

Traceback (most recent call last):
  File "C:\[...]\shark.py", line 98, in <module>
    main(sys.argv[1])
  File "C:\[...]\shark.py", line 93, in main
    fetch_forum()
  File "C:\[...]\shark.py", line 79, in fetch_forum
    fetch_user(user_url)
  File "C:\[...]\shark.py", line 42, in fetch_user
    backpacktf = check_backpacktf(steamID64)
  File "C:\[...]\shark.py", line 25, in check_backpacktf
    with requests.get(''.join([BACKPACKTF, steamID64])) as response:
AttributeError: __exit__


I'm trying to use the 'with statement' to reduce the SLOC and make the code prettier. Using 'try-expect-finally' wouldn't be good, as I have more 3 or 4 functions like this one that call different sites. What's the problem? Can't I use requests that way?
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Gmane