def fetch_details(self): data = str(self.properties).encode('ASCII') headers = {'Content-Type': 'application/json; charset=utf-8'} url = 'http://amoozesh.kanoon.ir/PlayForm.aspx/GetDocumentItem' req = request.Request(url=url, data=data, headers=headers) stream = request.urlopen(req) response = stream.read().decode('UTF-8') details = from_json(from_json(response)['d']) self._save_details(details)
def build_course_relations(db, filenames): 'Create relations between courses and their prerequisites and so on' for filename in filenames: data = from_json(open(filename).read()) for course_ident in data['courses']: res = db.execute(queries['find course by identifier'], (course_ident, )) course_id = res.fetchone()[0] for prereq_ident in data['courses'][course_ident]['prerequisites']: res = db.execute(queries['find course by identifier'], (prereq_ident, )) prereq = res.fetchone() if prereq is not None: prereq_id = prereq[0] db.execute(queries['add prerequisite'], (course_id, prereq_id)) for coreq_ident in data['courses'][course_ident]['corequisites']: res = db.execute(queries['find course by identifier'], (coreq_ident, )) coreq = res.fetchone() if coreq is not None: coreq_id = coreq[0] db.execute(queries['add corequisite'], (course_id, coreq_id)) for concur_ident in data['courses'][course_ident]['concurrent']: res = db.execute(queries['find course by identifier'], (concur_ident, )) concur = res.fetchone() if concur is not None: concur_id = concur[0] db.execute(queries['add concurrent'], (course_id, concur_id))
def get_dates(): with urlopen('https://rest.bandsintown.com/artists/damniam/events?app_id=damniam_website') as req: dates = from_json(req.read().decode()) for date in dates: date['raw_datetime'] = date['datetime'] date['datetime'] = build_date_str(date['datetime']) return dates
def wrapper(context, request, *args, **kwargs): for field_name in self.fields: data = request.data[field_name] if isinstance(data, str): data = from_json(data) request.data[field_name] = self.class_meta.get_field(field_name).rel.to.objects.get(pk=data['id']) return fn(context, request, *args, **kwargs)
def _getCurVersions(self): curVersions = {} response = urllib2.urlopen(self.pluginInfoURL) data = json.from_json(response.read()) for resource in data['resources']: curVersions[resource['title']] = resource['version_string'] return curVersions
def unpack_oi_link(oi_link): try: global oi_links oi_link = from_json(oi_links[oi_link]) oi_link_type = oi_link['oi_link_type'][0] oi_link_content = oi_link['oi_link_content'][0] if oi_link_type == 'short_link': if oi_link_content.startswith( 'https://') or oi_link_content.startswith('http://'): return redirect(oi_link_content) else: return redirect('http://' + oi_link_content) else: template = ''' <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <textarea style=" width: 100%; height: calc(100vh - 3rem); " readonly>{{ oi_link_content|escape }}</textarea> </body> </html> ''' return render_template_string(template, oi_link_content=oi_link_content) except: return abort(404)
def readconfig(self): res = {} with open(self.filepath) as f: data = f.read() if self.json: res = from_json(data) for key in res.keys(): res[key.lower()] = res[key] res[key.upper()] = res[key] else: lines = data.split('\n') # should make support for \r for line in lines: if len(line) > 0: if line[0] == '#': pass else: g = match('([\w@,./]+)\s*=\s*([\w@.,\-/:]+)', line) if g: res[(str(g.group(1))).lower()] = str( g.group(2)) res[(str(g.group(1))).upper()] = str( g.group(2)) res[(str(g.group(1)))] = str(g.group(2)) if not res: raise IOError( 'Could not read config file, no readable data in it (possibly wrong format)' ) return res
def dynamic_route(self): query = request.query_string if request.query_string else 'no_query_string' body = request.body.getvalue() if body: try: body = from_json(body) except (TypeError, Exception) as e: warn('The body in this request is not json: %s' % (e)) else: body = 'no_body' for dr in self.dynamic_routes: if dr['method'] != request.method: continue if dr['path'] != request.path: continue if dr['query'] != query: continue if dr['body'] != body: continue r = dr['response'] dr['received_requests'] = dr['received_requests'] + 1 break string_headers = {str(key): str(value) for key, value in r['headers'].iteritems()} return HTTPResponse(status=r['status'], body=r['body'], headers=string_headers)
def __new__(new_class, class_name, base_classes, args_file_name=None): new_class = type(class_name, base_classes, {}) if args_file_name is not None: with open(args_file_name, 'r') as args_file: args_dict = from_json(args_file.read()) for attr, value in args_dict.items(): setattr(new_class, attr, value) return new_class
def subscribe(queue): request_body = from_json(request.data) if(queue in subscriptions.queues): # the callback here should be a partially applied function which calls the uri subscriptions.subscribe(queue, request_body['callback']) return SUCCESS else: return "Queue not found", 400
def subscribe(queue): request_body = from_json(request.data) if (queue in subscriptions.queues): # the callback here should be a partially applied function which calls the uri subscriptions.subscribe(queue, request_body['callback']) return SUCCESS else: return "Queue not found", 400
def node_add(request): if not request.method == "POST": return HttpResponse('request shoud be POST, but it is %s' % str(request.method)) node_type = Type.objects.get(pk=request.POST['type']) values = request.POST['values'] parent = request.POST['parent'] create(node_type.name, from_json(values), parent) return HttpResponse('done')
def get_images(): def time_mapper(img): stamp = int(img['created_time']) iso_date = datetime.fromtimestamp(stamp).isoformat() img['created_time'] = build_date_str(iso_date) return img with urlopen('https://api.instagram.com/v1/users/self/media/recent/?access_token=328950673.93e3299.50f6a823351144fa89ff552524d343c6&count=16&date_format=U') as req: data = from_json(req.read().decode())['data'] return list(map(time_mapper, data))
def store_information(db, filenames): 'Store the information about courses in a list of json files' for filename in filenames: data = from_json(open(filename).read()) dept_id = store_department_information(db, data['name'], data['identifier']) for identifier in data['courses']: store_course_information(db, dept_id, identifier, data['courses'][identifier])
def agent_fn(): global watering # Gather data from sensors s.write(b's') value = from_json(s.readline()) # If the moisture is lower than the threshold, recollect the data and irrigate if needed if not watering: if value['moisture'] < moisture: try: w = WeatherRecord( date = strftime(b'%m/%d/%Y %H:%M:%S', datetime.now().timetuple()), humidity = value['humidity'], pressure = value['pressure'], temperature = value['temperature'], water = False ) # Use classifier to attempt to predict output values if tree.classify(w, default = False): s.write(b'r') watering = from_json(s.readline())['active'] else: # Employ sensor data to perform an action if needed t = datetime.strptime(w.date, b'%m/%d/%Y %H:%M:%S') if (6 <= t.hour < 10) or (17 <= t.hour < 19): if (w.humidity < 60.0) and (w.pressure < 1010.0) and (w.temperature > 15.5): s.write(b'r') watering = from_json(s.readline())['active'] except BaseException: raise KeyboardInterrupt() else: # If we're watering, we should stop s.write(b'r') watering = from_json(s.readline())['active']
def __record_to_issue(db_record): issue = JiraIssue() issue.parse_args( key=db_record.key, reporter=db_record.reporter, summary=db_record.summary, status=db_record.status, dc_status=db_record.dc_status, custom_fields=from_json(db_record.custom_fields), ) return issue
def build_content(path, redis_object=None, content_type='page'): if redis_object is None: global ALL_CONTENT redis_object = ALL_CONTENT redis_key = join(content_type, path) print('++++++++build_content -> redis_key', redis_key) if not redis_key in redis_object: print('caching', redis_key) redis_object[redis_key] = to_json(_build_content(path, content_type)) else: print('from cache:', redis_key) return from_json(redis_object[redis_key])
def work(self): while Gtk.events_pending(): Gtk.main_iteration() # again = False msg = self.web_recv() if msg: try: msg = from_json(msg) print('This is the message %s' % (msg)) except BaseException: msg = None # again = True if msg == 'exit': self.close_application(None)
def web_recv(ws, msg): global global_msg if 'connected' in msg: web_send('["populate home table", %s]' % app.get_home_page_table()) else: if msg[-1] != '}': global_msg += msg elif global_msg != '': msg = global_msg + msg global_msg = '' if msg[-1] == '}': msg = from_json(msg) do_message(msg, web_send)
def work(self): while Gtk.events_pending(): Gtk.main_iteration() again = False msg = self.web_recv() if msg: try: msg = from_json(msg) print('This is the message %s'%(msg)) except: msg = None again = True if msg == 'exit': self.close_application(None)
def title_changed(self, widget, frame, title): if title != 'null': self.message_queue.put(title) while Gtk.events_pending(): Gtk.main_iteration() msg = self.web_recv() if msg: try: msg = from_json(msg) print('This is the message %s'%(msg)) if msg['status'] == 'ready': self.web_send('title="%s";subtitle="%s";humidity=%s;cloudiness=%s;temperature=%s;draw_graph(title,subtitle,temperature,humidity,cloudiness);'%(self.title,self.subtitle,self.humidity,self.cloudiness,self.temperature)) elif msg['status'] == 'exit': self.close_application(None) except: pass
def title_changed(self, widget, frame, title): if title != 'null': self.message_queue.put(title) while Gtk.events_pending(): Gtk.main_iteration() msg = self.web_recv() if msg: try: msg = from_json(msg) print('This is the message %s' % (msg)) if msg['status'] == 'ready': self.web_send('title="%s";subtitle="%s";humidity=%s;\ cloudiness=%s;temperature=%s;draw_graph(title,subtitle,temperature,humidity,\ cloudiness);' % (self.title, self.subtitle, self.humidity, self.cloudiness, self.temperature)) elif msg['status'] == 'exit': self.close_application(None) except: pass
def _run_post_interaction(self, request): interaction = from_json(request.body.read()) pact_request = interaction['request'] pact_response = interaction['response'] path = pact_request['path'] method = pact_request['method'].upper() methods = [] description = interaction['description'] provider_state = interaction['provider_state'] query = pact_request.get('query', 'no_query_string') body = pact_request.get('body', 'no_body') pact_response.setdefault('headers', {}) pact_response.setdefault('status', 200) pact_response.setdefault('body', '') if not len(self.dynamic_routes): self.append_route(description, provider_state, method, path, query, body, pact_response) else: match = False for dr in self.dynamic_routes: if (dr['description'] == description and dr['provider_state'] == provider_state and dr['method'] == method and dr['path'] == path and dr['query'] == query and dr['body'] == body and dr['response'] == pact_response): dr['expected_requests'] = dr['expected_requests'] + 1 match = True break if not match: self.append_route(description, provider_state, method, path, query, body, pact_response) methods = [r.get('method') for r in self.dynamic_routes if r.get('path') == path] self._app.route(path, methods, self.dynamic_route) self.registered_interactions.update(interaction) return 'Processed Interactions'
dump(tree, f) else: # The standard boot mode is selected if bool(args.moisture) is False: raise ValueError('Missing moisture threshold value') elif bool(args.src) is False: raise ValueError('Missing source port value') # Obtain initialization arguments moisture = max(0.0, min(1.0, args.moisture)) src = args.src time = max(0.0, args.scan_time) # Initialize serial port and check if terminal is active, log system initialization s = Serial(src, 9600) version = from_json(s.readline()) logging.info('Version: %s' % version['version']) logging.info('Refresh interval: %i ms' % time) logging.info('Moisture threshold: %.2f' % moisture) # Deserialize current tree structure with open('tree.dat', 'rb') as f: from cPickle import load tree = load(f) # Initialize agent with tree and start loop from apscheduler.schedulers.blocking import BlockingScheduler try:
def initialize(self, *args, **kwargs): value = super(BaseHandler, self).initialize(*args, **kwargs) self.params = from_json(self.request.body) return value