Skip to content

Commit aca5fd7

Browse files
authored
SG-24976 Update AMI Documentation To_Support Python 3 (#258)
* Updating AMI documentation example to run with Python 2/3. * Linting code example.
1 parent b9f066c commit aca5fd7

1 file changed

Lines changed: 59 additions & 55 deletions

File tree

docs/cookbook/examples/ami_handler.rst

Lines changed: 59 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ via ``POST``. If you're using a custom protocol the data is sent via ``GET``.
5757
'sort_direction': 'desc',
5858
'project_id': '4',
5959
'session_uuid': 'd8592bd6-fc41-11e1-b2c5-000c297a5f50',
60-
'column_display_names':
60+
'column_display_names':
6161
[
6262
'Version Name',
6363
'Thumbnail',
@@ -71,19 +71,19 @@ via ``POST``. If you're using a custom protocol the data is sent via ``GET``.
7171
]
7272
}
7373

74-
This simple class parses the url into easy to access types variables from the parameters,
75-
action, and protocol sections of the url. This example url
74+
This simple class parses the url into easy to access types variables from the parameters,
75+
action, and protocol sections of the url. This example url
7676
myCoolProtocol://doSomethingCool?user_id=123&user_login=miled&title=All%20Versions&...
7777
would be parsed like this:
7878

7979
(string) protocol: myCoolProtocol
8080
(string) action: doSomethingCool
8181
(dict) params: user_id=123&user_login=miled&title=All%20Versions&...
82-
82+
8383
The parameters variable will be returned as a dictionary of string key/value pairs. Here's
8484
how to instantiate:
8585

86-
sa = ShotgunAction(sys.argv[1]) # sys.argv[1]
86+
sa = ShotgunAction(sys.argv[1]) # sys.argv[1]
8787

8888
sa.params['user_login'] # returns 'miled'
8989
sa.params['user_id'] # returns 123
@@ -95,66 +95,66 @@ via ``POST``. If you're using a custom protocol the data is sent via ``GET``.
9595
# Imports
9696
# ---------------------------------------------------------------------------------------------
9797
import sys, os
98-
import urllib
98+
import six
9999
import logging as logger
100100

101-
from pprint import pprint
102-
103101
# ---------------------------------------------------------------------------------------------
104102
# Variables
105103
# ---------------------------------------------------------------------------------------------
106104
# location to write logfile for this script
107105
# logging is a bit of overkill for this class, but can still be useful.
108-
logfile = os.path.dirname(sys.argv[0])+"/shotgun_action.log"
106+
logfile = os.path.dirname(sys.argv[0]) + "/shotgun_action.log"
109107

110108

111109
# ----------------------------------------------
112110
# Generic ShotgunAction Exception Class
113111
# ----------------------------------------------
114112
class ShotgunActionException(Exception):
115113
pass
116-
114+
117115

118116
# ----------------------------------------------
119117
# ShotgunAction Class to manage ActionMenuItem call
120118
# ----------------------------------------------
121-
class ShotgunAction():
122-
119+
class ShotgunAction:
123120
def __init__(self, url):
124121
self.logger = self._init_log(logfile)
125122
self.url = url
126-
self.protocol, self.action, self.params = self._parse_url()
127-
123+
self.protocol, self.action, self.params = self._parse_url()
124+
128125
# entity type that the page was displaying
129-
self.entity_type = self.params['entity_type']
126+
self.entity_type = self.params["entity_type"]
130127

131128
# Project info (if the ActionMenuItem was launched from a page not belonging
132129
# to a Project (Global Page, My Page, etc.), this will be blank
133-
if 'project_id' in self.params:
134-
self.project = { 'id':int(self.params['project_id']), 'name':self.params['project_name'] }
130+
if "project_id" in self.params:
131+
self.project = {
132+
"id": int(self.params["project_id"]),
133+
"name": self.params["project_name"],
134+
}
135135
else:
136136
self.project = None
137137

138138
# Internal column names currently displayed on the page
139-
self.columns = self.params['cols']
139+
self.columns = self.params["cols"]
140140

141141
# Human readable names of the columns currently displayed on the page
142-
self.column_display_names = self.params['column_display_names']
142+
self.column_display_names = self.params["column_display_names"]
143143

144144
# All ids of the entities returned by the query (not just those visible on the page)
145145
self.ids = []
146-
if len(self.params['ids']) > 0:
147-
ids = self.params['ids'].split(',')
146+
if len(self.params["ids"]) > 0:
147+
ids = self.params["ids"].split(",")
148148
self.ids = [int(id) for id in ids]
149-
149+
150150
# All ids of the entities returned by the query in filter format ready
151151
# to use in a find() query
152152
self.ids_filter = self._convert_ids_to_filter(self.ids)
153153

154154
# ids of entities that were currently selected
155155
self.selected_ids = []
156-
if len(self.params['selected_ids']) > 0:
157-
sids = self.params['selected_ids'].split(',')
156+
if len(self.params["selected_ids"]) > 0:
157+
sids = self.params["selected_ids"].split(",")
158158
self.selected_ids = [int(id) for id in sids]
159159

160160
# All selected ids of the entities returned by the query in filter format ready
@@ -163,84 +163,88 @@ via ``POST``. If you're using a custom protocol the data is sent via ``GET``.
163163

164164
# sort values for the page
165165
# (we don't allow no sort anymore, but not sure if there's legacy here)
166-
if 'sort_column' in self.params:
167-
self.sort = { 'column':self.params['sort_column'], 'direction':self.params['sort_direction'] }
166+
if "sort_column" in self.params:
167+
self.sort = {
168+
"column": self.params["sort_column"],
169+
"direction": self.params["sort_direction"],
170+
}
168171
else:
169172
self.sort = None
170-
173+
171174
# title of the page
172-
self.title = self.params['title']
175+
self.title = self.params["title"]
173176

174177
# user info who launched the ActionMenuItem
175-
self.user = { 'id':self.params['user_id'], 'login':self.params['user_login']}
178+
self.user = {"id": self.params["user_id"], "login": self.params["user_login"]}
176179

177180
# session_uuid
178-
self.session_uuid = self.params['session_uuid']
181+
self.session_uuid = self.params["session_uuid"]
179182

180183
# ----------------------------------------------
181184
# Set up logging
182185
# ----------------------------------------------
183-
def _init_log(self, filename="shotgun_action.log"):
186+
def _init_log(self, filename="shotgun_action.log"):
184187
try:
185-
logger.basicConfig(level=logger.DEBUG,
186-
format='%(asctime)s %(levelname)-8s %(message)s',
187-
datefmt='%Y-%b-%d %H:%M:%S',
188-
filename=filename,
189-
filemode='w+')
190-
except IOError, e:
191-
raise ShotgunActionException ("Unable to open logfile for writing: %s" % e)
192-
logger.info("ShotgunAction logging started.")
193-
return logger
194-
188+
logger.basicConfig(
189+
level=logger.DEBUG,
190+
format="%(asctime)s %(levelname)-8s %(message)s",
191+
datefmt="%Y-%b-%d %H:%M:%S",
192+
filename=filename,
193+
filemode="w+",
194+
)
195+
except IOError as e:
196+
raise ShotgunActionException("Unable to open logfile for writing: %s" % e)
197+
logger.info("ShotgunAction logging started.")
198+
return logger
199+
200+
# ----------------------------------------------
195201

196-
# ----------------------------------------------
197202
# Parse ActionMenuItem call into protocol, action and params
198203
# ----------------------------------------------
199204
def _parse_url(self):
200-
logger.info("Parsing full url received: %s" % self.url)
205+
logger.info("Parsing full url received: %s" % self.url)
201206

202-
# get the protocol used
207+
# get the protocol used
203208
protocol, path = self.url.split(":", 1)
204209
logger.info("protocol: %s" % protocol)
205-
206-
# extract the action
210+
211+
# extract the action
207212
action, params = path.split("?", 1)
208213
action = action.strip("/")
209214
logger.info("action: %s" % action)
210215

211216
# extract the parameters
212217
# 'column_display_names' and 'cols' occurs once for each column displayed so we store it as a list
213218
params = params.split("&")
214-
p = {'column_display_names':[], 'cols':[]}
219+
p = {"column_display_names": [], "cols": []}
215220
for arg in params:
216-
key, value = map(urllib.unquote, arg.split("=", 1))
217-
if key == 'column_display_names' or key == 'cols' :
221+
key, value = map(six.moves.urllib.parse.unquote, arg.split("=", 1))
222+
if key == "column_display_names" or key == "cols":
218223
p[key].append(value)
219224
else:
220225
p[key] = value
221226
params = p
222227
logger.info("params: %s" % params)
223228
return (protocol, action, params)
224-
225-
229+
226230
# ----------------------------------------------
227231
# Convert IDs to filter format to us in find() queries
228232
# ----------------------------------------------
229233
def _convert_ids_to_filter(self, ids):
230234
filter = []
231235
for id in ids:
232-
filter.append(['id','is',id])
236+
filter.append(["id", "is", id])
233237
logger.debug("parsed ids into: %s" % filter)
234238
return filter
235-
239+
236240

237241
# ----------------------------------------------
238242
# Main Block
239243
# ----------------------------------------------
240244
if __name__ == "__main__":
241245
try:
242246
sa = ShotgunAction(sys.argv[1])
243-
logger.info("ShotgunAction: Firing... %s" % (sys.argv[1]) )
244-
except IndexError, e:
247+
logger.info("ShotgunAction: Firing... %s" % (sys.argv[1]))
248+
except IndexError as e:
245249
raise ShotgunActionException("Missing GET arguments")
246250
logger.info("ShotgunAction process finished.")

0 commit comments

Comments
 (0)