def post(self, request): data = request.POST try: print "uname:" , data['uName'] print "uPin:" , data['uPin'] print "MSISDN:" , data['MSISDN'] print "messageString:" , data['messageString'] #print "Display:", data['Display'] #print "udh:", data['udh'] #print "mwi:", data['mwi'] #print "coding:", data['coding'] if str.isdigit(data['MSISDN']) == False: print "Bad MSISDN : " , data['MSISDN'] callback(data['uName'], "STRATLOC") return http.ok([('Content-Type', 'text/html')], "<return>501</return>") print "----------------------------------------" #wait until modem becomes available print "Lock : " , gsmlock if (gsmlock == True): print "waiting for modem to become available" while (gsmlock == True): pass modem_sendmsg(data['MSISDN'] , data['messageString']) return http.ok([('Content-Type', 'text/html')], "<return>201</return>") except: return http.ok([('Content-Type', 'text/html')], "<return>506</return>")
def all(self, request): if request.method == "DELETE": return http.ok([('Content-Type', 'text/plain')], "THERE IS NO DELETE") else: return http.ok([('Content-Type', 'text/plain')], request.method)
def resource(request): def gen(): yield "Three ... " yield "two ... " yield "one ... " yield "BANG!" return http.ok([('Content-Type', 'text/plain')], gen())
def render_response(request, page, template, args={}, type='text/html', encoding='utf-8', headers=[]): """ Render a page, using the template and args, and return a '200 OK' response. The response's Content-Type header will be constructed from the type and encoding. :arg request: Request instance. :arg page: Page being rendered (hint, it's often self). :arg template: Name of the template file. :arg args: Dictionary of args to pass to the template renderer. :arg type: Optional mime type of content, defaults to 'text/html' :arg encoding: Optional encoding of output, default to 'utf-8'. :arg headers: Optional extra HTTP headers for the output, default to [] """ # Copy the headers to avoid changing the arg default or the list passed by # the caller. headers = list(headers) headers.extend([('Content-Type', '%s; charset=%s' % (type, encoding))]) return http.ok(headers, render_page(request, page, template, args, encoding=encoding))
def index(self, request, segments): def g(): if isinstance(self.metadata, dict): for k,v in sorted(self.metadata.iteritems()): if isinstance(v, dict): yield '{0}/\n'.format(k) elif isinstance(v, list): yield '{0}/\n'.format(k) else: yield '{0}\n'.format(k) elif isinstance(self.metadata, list): for i, v in enumerate(self.metadata): # it always needs some name (or cloud-init will # write "0=" into ssh authorized_keys), so provide # the index as a default name = '{0}'.format(i) if isinstance(v, Named): name = v.name yield '{0}={1}\n'.format(i, name) else: raise RuntimeError('Cannot index weird metadata: %r' % self.metadata) return http.ok( [('Content-Type', 'text/plain')], g(), )
def GET(self, request): C = request.environ["couchish"] with C.session() as S: photos = list(S.view("photo/all", include_docs=True)) photos = [p.doc for p in photos] photos.sort(key=itemgetter("ref")) out = dictwriter(photos, CSVPHOTOKEYS) return http.ok([("Content-Type", "text/csv")], out)
def GET(self, request): C = request.environ["couchish"] with C.session() as S: users = list(S.view("user/all", include_docs=True)) users = [p.doc for p in users] users.sort(key=itemgetter("last_name")) out = dictwriter(users, CSVUSERKEYS) return http.ok([("Content-Type", "text/csv")], out)
def serve(self, request): if isinstance(self.metadata, (dict, list)): return http.not_found() else: return http.ok( [('Content-Type', 'text/plain')], [self.metadata], )
def __call__(self, request): log.debug('formish.FileResource: in File Resource') if not self.segments: return None # This is our input filepath requested_filepath = self._get_requested_filepath() log.debug('formish.FileResource: requested_filepath=%s',requested_filepath) # Get the raw cache file path and mtime raw_cached_filepath = self._get_cachefile_path(requested_filepath) log.debug('formish.FileResource: raw_cached_filepath=%s',raw_cached_filepath) raw_cached_mtime = self._get_file_mtime(raw_cached_filepath) # Check to see if fa and temp exist tempfile_path = self._get_tempfile_path(requested_filepath) log.debug('formish.FileResource: tempfile_path=%s',tempfile_path) # work out which has changed most recently (if either is newer than cache) fileaccessor_mtime = self._get_fileaccessor_mtime(requested_filepath) tempfile_mtime = self._get_file_mtime(tempfile_path) source_mtime = max(fileaccessor_mtime, tempfile_mtime) # unfound files return a 1970 timestamp for simplicity, if we don't have files newer than 1971, bugout if source_mtime < datetime(1971,1,1,0,0): return None if source_mtime > raw_cached_mtime: if fileaccessor_mtime > tempfile_mtime: log.debug('formish.FileResource: fileaccessor resource is newer. rebuild raw cache') filedata = self.fileaccessor.get_file(requested_filepath) mimetype = self.fileaccessor.get_mimetype(requested_filepath) else: log.debug('formish.FileResource: tempfile resource is newer. rebuilding raw cache') filedata = open(tempfile_path).read() mimetype = get_mimetype(tempfile_path) open(raw_cached_filepath,'w').write(filedata) else: log.debug('formish.FileResource: raw cache file is valid') mimetype = get_mimetype(raw_cached_filepath) # If we're trying to resize, check mtime on resized_cache size_suffix = self._get_size_suffix(request) if size_suffix: log.debug('formish.FileResource: size_suffix=%s',size_suffix) cached_filepath = self._get_cachefile_path(requested_filepath, size_suffix) cached_mtime = self._get_file_mtime(cached_filepath) log.debug('formish.FileResource: cached_filepath=%s',cached_filepath) if not os.path.exists(cached_filepath) or source_mtime > cached_mtime: width, height = get_size_from_dict(request.GET) log.debug('formish.FileResource: cache invalid. resizing image') resize_image(raw_cached_filepath, cached_filepath, width, height) else: log.debug('formish.FileResource: resized cache file is valid.') cached_filepath = raw_cached_filepath return http.ok([('content-type', mimetype )], open(cached_filepath, 'rb').read())
def serve(self, request): f = pkg_resources.resource_stream( 'teuthology.html', 'root.html', ) return http.ok( [('Content-Type', 'text/html')], f, )
def user_data(self, request, segments): if segments: return None data = request.environ['cheesy2.userdata'](request) if data is not None: return http.ok( [('Content-Type', 'text/plain')], [data], )
def status(self, request): session = models.Session.get_by_key_name(self.name) if session is None: return http.not_found([], '') return http.ok( [('Content-Type', 'application/json')], json.dumps({'created_at': str(session.created_at)}) )
def details(self, request): try: request_id = int(self._request_id) except ValueError: return http.bad_request() resource = self._make_resource(request_id) if resource is None: return http.not_found() return http.ok([], etag(resource))
def html(self, request): C = request.environ['couchish'] with C.session() as S: results = list(S.view('page/by_url',key='/',include_docs=True)) news = S.docs_by_view('newsitem/homepage_news') news = [n for n in news if n.get('date') and n['date'] < date.today()] page = results[0].doc sitemap = navigation.get_navigation(request) data = {'page': page, 'request': request, 'sitemap': sitemap, 'news':news} out = templating.render(request, page['pagetype'], data, encoding='utf-8') return http.ok([('Content-Type', 'text/html')], out)
def details(self, request): try: request_id = int(self._request_id) except ValueError: return http.bad_request() resource = self._make_resource(request_id, MEMBERSHIP_CHANGE_REQUESTS) if resource is None: return http.not_found() # Remove unnecessary keys. del resource['key'] return http.ok([], etag(resource))
def json(self, req): filter_indexname = req.params.get('indexname', None) base_url = '/'.join(req.url.split('/')[:-2]) indexes = [] for x in self.pypi.get_indexes(self.distro.distro_id): if not filter_indexname: indexes.append(x) continue if filter_indexname == x: index = Index(self.pypi, self.distro, x) indexes.append(index.get_index_dict(base_url)) return http.ok([], simplejson.dumps({'indexes': indexes}))
def scrape(self, request): session = models.Session.get_by_key_name(self.name) if session is None: return http.not_found([], '') data = json.loads(request.body) content, matched = session.scrape(data['url'], data['match']) return http.ok( [('Content-Type', 'application/json')], json.dumps({'content': content, 'matched': matched}) )
def get_configuration(self, request): """Get a mailing list configuration.""" resource = {} if self._attribute is None: # Return all readable attributes. for attribute in ATTRIBUTES: value = ATTRIBUTES[attribute].get(self._mlist, attribute) resource[attribute] = value elif self._attribute not in ATTRIBUTES: return http.bad_request([], b"Unknown attribute: {0}".format(self._attribute)) else: attribute = self._attribute value = ATTRIBUTES[attribute].get(self._mlist, attribute) resource[attribute] = value return http.ok([], etag(resource))
def find(self, request): """Find a member""" service = getUtility(ISubscriptionService) validator = Validator( list_id=unicode, subscriber=unicode, role=enum_validator(MemberRole), _optional=('list_id', 'subscriber', 'role')) members = service.find_members(**validator(request)) # We can't just return the _FoundMembers instance, because # CollectionMixins have only a GET method, which is incompatible with # this POSTed resource. IOW, without doing this here, restish would # throw a 405 Method Not Allowed. resource = _FoundMembers(members)._make_collection(request) return http.ok([], etag(resource))
def system(self, request, segments): """/<api>/system""" if len(segments) == 0: resource = dict( mailman_version=system.mailman_version, python_version=system.python_version, self_link=path_to('system'), ) elif len(segments) > 1: return http.bad_request() elif segments[0] == 'preferences': return ReadOnlyPreferences(system_preferences, 'system'), [] else: return http.bad_request() return http.ok([], etag(resource))
def preferences(self, segments): resource = dict() for attr in PREFERENCES: # Handle this one specially. if attr == 'preferred_language': continue value = getattr(self._parent, attr, None) if value is not None: resource[attr] = value # Add the preferred language, if it's not missing. preferred_language = self._parent.preferred_language if preferred_language is not None: resource['preferred_language'] = preferred_language.code # Add the self link. resource['self_link'] = path_to( '{0}/preferences'.format(self._base_url)) return http.ok([], etag(resource))
def details(self, request): requests = IListRequests(self._mlist) try: request_id = int(self._request_id) except ValueError: return http.bad_request() results = requests.get_request(request_id, RequestType.held_message) if results is None: return http.not_found() key, data = results msg = getUtility(IMessageStore).get_message_by_id(key) resource = dict( key=key, data=data, msg=msg.as_string(), id=request_id, ) return http.ok([], etag(resource))
def lists(self, request, segments): """/<api>/lists /<api>/lists/<list> /<api>/lists/<list>/... """ if len(segments) == 0: return AllLists() elif len(segments) == 1 and segments[0] == 'styles': manager = getUtility(IStyleManager) style_names = sorted(style.name for style in manager.styles) resource = dict(style_names=style_names, default=config.styles.default) return http.ok([], etag(resource)) else: # list-id is preferred, but for backward compatibility, # fqdn_listname is also accepted. list_identifier = segments.pop(0) return AList(list_identifier), segments
def save(self, req): distro_id = self.distro.distro_id indexname = self.indexname updated = simplejson.loads(req.body or '{}') entries = updated['entries'] if self.pypi.index_manager.has_index(distro_id, indexname): self.pypi.index_manager.remove_index(distro_id, indexname) for x in entries: target_name, opt, target_version = utils.parse_req_parts(x) if opt not in ('==', '='): raise ValueError('Bad req option "%s" for "%s"' % (str(opt), x)) target_distro_id = utils.make_distro_id(target_name) self.pypi.index_manager.add_index_item(distro_id, indexname, target_distro_id, target_version) return http.ok([], simplejson.dumps({'entries': entries}))
def GET(self, request): """ http://localhost:8080/example?nd=1234901751220&_search=false&rows=10&page=1&sidx=url&sord=desc nd """ C = request.environ['couchish'] M = request.environ['adminish']['page'] T = C.config.types['page'] try: page = int(request.GET.get('page')) except ValueError: page = 0 try: numrows = int(request.GET.get('rows')) except ValueError: numrows = 10 sortkey = request.GET.get('sidx') reverse = request.GET.get('sord') if reverse == 'asc': reverse = False else: reverse = True with C.session() as S: items = S.docs_by_type('page') items = list(items) items = sorted(items, key=itemgetter(sortkey), reverse=reverse) records = len(items) total_pages = int(math.ceil( float(records) / int(numrows) )) if page > total_pages: page = total_pages start = (page-1) * numrows end = page * numrows results = {'page': int(page), 'total': int(total_pages), 'records': records} rows = [] for item in items[start:end]: rows.append( {'id':item['url'], 'cell':[item['url'], item['title']]} ) results['rows'] = rows return http.ok([('Content-Type','text/javascript'),], couchish.jsonutil.dumps(results) )
def put(self, req): distro_id = self.distro.distro_id updated = simplejson.loads(req.body or '{}') altered = [] for indexdict in updated['indexes']: indexname = indexdict['indexname'] altered.append(indexname) entries = indexdict['entries'] self.pypi.index_manager.remove_index(distro_id, indexname) for x in entries: target_name, opt, target_version = utils.parse_req_parts(x) if opt not in ('==', '='): raise ValueError('Bad req option "%s" for "%s"' % (str(opt), x)) target_distro_id = utils.make_distro_id(target_name) self.pypi.index_manager.add_index_item(distro_id, indexname, target_distro_id, target_version) return http.ok([], simplejson.dumps({'indexes': altered}))
class Preseed(resource.Resource): @resource.child(resource.any) def preseed(self, request, segments): if segments[1:]: return None name = segments[0] name = name.replace('.', '_') try: f = pkg_resources.resource_stream( 'cheesy2.preseed', '{0}.preseed'.format(name), ) except IOError, e: if e.errno == errno.ENOENT: return None else: raise return http.ok( [('Content-Type', 'text/plain')], f, )
def json(self, req): page_num = int(req.params.get('page_num', 1)) search = req.params.get('search', None) distreq = req.params.get('req', None) base_url = req.url if distreq: reqs = self.pypi.find_req(distreq) distros = [] for d, files in reqs: distros.append({'id': d.distro_id, 'name': d.name, 'last_updated': simple_ser(d.last_updated), 'summary': d.summary, 'files': [{'filename': os.path.basename(f), 'url': req.relative_url(d.distro_id + '/f/'+os.path.basename(f), True), 'version': v} for f, v in files]}) total_pages = -1 page_num = -1 else: if search: results = self.pypi.search(search) else: results = self.pypi.get_distros('last_updated desc') page = utils.Page(results, page_num, 20) distros = [{'id': x.distro_id, 'name': x.name, 'last_updated': simple_ser(x.last_updated), 'summary': x.summary} for x in page.results] total_pages = page.total_pages page_num = page.page_num jsonres = {'distros': distros, 'total_pages': total_pages, 'page_num': page_num} if search: jsonres['search'] = search return http.ok([], simplejson.dumps(jsonres))
def GET(self, request): C = request.environ["couchish"] with C.session() as S: rows = list(S.view("product/all", include_docs=True)) products = [] options = {} for row in rows: product = row.doc options[product["code"]] = list(product["pricing"]) del product["pricing"] del product["photo"] if "sizes" in product: del product["sizes"] products.append(product) products.sort(key=itemgetter("code")) out = [] out.append(CSVPRODUCTKEYS) for product in products: row = [product.get(k, "") for k in CSVPRODUCTKEYS] out.append(row) for option in options[product["code"]]: row = [option.get(k, "#") for k in CSVOPTIONKEYS] out.append(row) return http.ok([("Content-Type", "text/csv")], listwriter(out))
def bbb(self, request): return http.ok([('Content-Type', 'text/html')], '')
def __call__(self, request): return http.ok([('Content-Type', 'text/plain')], self.body)
def static_child(self, request, segments): return http.ok([('Content-Type', 'text/plain')], 'static')
def __call__(self, request): body = '%r %r' % (self.segments, self.args) return http.ok([('Content-Type', 'text/plain')], body)
def __call__(self, request): return http.ok([('Content-Type', 'text/plain')], '%r' % (self.segments, ))
def html(self, request): return http.ok([('Content-Type', 'text/plain')], 'Hello!')
def user(self, request): """Return a single user end-point.""" if self._user is None: return http.not_found() return http.ok([], self._resource_as_json(self._user))
def aaa(self, request): return http.ok([('Content-Type', 'application/json')], '')
def json_in_json_out(self, request): return http.ok([('Content-Type', 'application/json')], 'json_in_json_out')
def json_in_html_out(self, request): return http.ok([], 'json_in_html_out')
def anything(self, request): return http.ok([('Content-Type', 'image/png')], '*/*')
def image_png(self, request): return http.ok([('Content-Type', 'image/png')], 'image/png')
def xml(self, request): return http.ok([('Content-Type', 'application/xml')], 'xml')
def test_root_is_a_response(self): A = app.RestishApp(http.ok([('Content-Type', 'text/plain')], 'foobar')) R = webtest.TestApp(A).get('/foo') assert R.body == 'foobar'
def json(self, request): return http.ok([('Content-Type', 'application/json')], "{}")
def func(request): return http.ok([], 'Hello')
def __call__(self, request): return http.ok([('Content-Type', 'text/plain')], '/'.join(self.segments).encode('utf-8'))
def html(self, request): return http.ok([], '<html />')
def anything(self, request): return http.ok([('Content-Type', 'text/html')], '<p>Hello!</p>')
def foo(self, request, segments): return http.ok([('Content-Type', 'text/plain')], 'foobar')
def GET(self, request): return http.ok([('Content-Type', 'text/plain')], self.match.encode('utf-8'))
def html(self, request): return http.ok([], '<p>Hello!</p>')
def html(self, request): return http.ok([('Content-Type', 'text/html')], "<html />")
def collection(self, request): """/users""" resource = self._make_collection(request) return http.ok([], etag(resource))
def json(self, request): return http.ok([], '"Hello!"')