def unauthorized(request, exception): ''' This function handles 401 errors. Since no other part of the itty framework throws 401 errors it is safe to assume that all exceptions are json encoded. ''' # Ensure that the exception is json encoded. assert isinstance(exception, JsonUnauthorized) == True # All exceptions handled by this function are json encoded 401 errors. content_type = 'application/json' status = 401 headers = [] # WWW-Authenticate header is returned to tell the client which # Authorization schemes are applicable to this resource. First, check the # auth entry point. if match(AUTH, request.path) != None: headers.append(('WWW-Authenticate', AUTH_AUTHORIZATION_HEADER)) # Check the validate entry point. elif match(VALIDATE, request.path) != None: headers.append(('WWW-Authenticate', SESSION_AUTHORIZATION_HEADER)) # The content is json encoded by the report_error function in utils.py. # In order to report the error, simply cast the error as a string. content = unicode(exception).encode('utf-8', 'replace') response = Response(content, headers, status, content_type) return response.send(request._start_response)
def index(request): macaddress = request.GET['macaddress'] location = request.GET['location'] cur = con.cursor() sql_insert = """INSERT IGNORE INTO user_location(macaddress, location_id) VALUES ("""+"'"+ macaddress+ "'" +""","""+location+""")""" sql_lookup = "Select * from user_location where macaddress = " + "'" + macaddress + "'" + " and location_id =" + location sql_location = "Select name from location where id =" + location sql_number = "Select telefonnr from user a where a.macaddress ='" + macaddress + "'" with con: cur.execute(sql_lookup) if len(cur.fetchall())==0: cur.execute(sql_insert) cur.execute(sql_location) rows = cur.fetchall() files = [] for row in rows: files.append(row[0]) cur.execute(sql_number) number = cur.fetchall()[0][0] #url = 'http://sms77.de/gateway/?u=eVoDesign&p=19058c741457f13eb397607f6d4d56d5&to=00491608071336&text=Sie wurden fuer die Location+' + row[0] + '+freigeschaltet&type=quality&from=spacetime' url = 'https://tropo.developergarden.com/api/sessions?action=create&token=4e427865446b4f6f77466e4b4a786d61536b626d57556b625a4472414664424950614671495453614a494c71&msg=Die Location ' + row[0] + ' wurde freigeschaltet spacetime-box://content/&number='+number print url requests.get(url) #print test.text #print row[0] return Response("SMS VERSENDEN") return Response("...")
def internal_error(request, exception): ''' This function handles all 500 type errors before they are sent back to the requester. 5xx type HTTP errors should be accompanied by an error report. While it is not necessary or feasible (HTTP Proxies can generate errors, for example) to handle all exception types, handling the HTTP 500 exception explicitly lets the publisher control the debugging information exposed. Some web frameworks may be verbose about an http 500 error, providing detailed debugging information that may compromise the system. It is up to the publisher to ensure that these features are well controlled. If the Polar server receives a 5xx error that does not have a report, it will first try to decode the body of the post request using json. This process will fail, and the server will then store the body of the post request (as opposed to its error code, message and resource) and continue processing. Server Errors: This section documents errors that are persisted on the server and not sent to the client. Note that the publisher is free to modify the content of these messages as they please. InternalError: Thrown when no exception object is provided (the nature of the exception is unknown). Code: InternalError Message: An error occurred. Please contact support. Message: An internal server error occurred. Please check logs. HTTP Error Code: 500 Required: No ''' # All exceptions handled by this function are json encoded 500 errors. content_type = 'application/json' status = 500 headers = [] # The content is determined below. content = '' # HTTP 500 exceptions may be of any type. If the type is JsonAppError then # the exception has been json encoded. If it is not, then we need to # substitute the message with a default message. if isinstance(exception, JsonAppError) == True: content = unicode(exception).encode('utf-8', 'replace') # If the exception is not a JsonAppError exception, then send a generic # exception. else: url = request.path code = 'InternalError' message = 'An error occurred. Please contact support.' debug = 'An internal server error occurred. Please check logs.' content = encode_error(url, code, message, debug) response = Response(content, headers, status, content_type) return response.send(request._start_response)
def not_found(request, exception): ''' This function handles any uncaught HTTP 404 errors. Remember that 4xx type HTTP errors should be accompanied by an error report. A 404 error is a common error for many web frameworks; particularly those that use regex to route requests. Returning a proper error report makes diagnosing such problems easier. If the Polar server receives a 4xx error that does not have a report, it will first try to decode the body of the post request using json. This process will fail, and the server will then store the body of the post request (as opposed to its error code, message and resource) and continue processing. Errors: NoHandler: Thrown when the URL could not be routed to a handler. This error code should be thrown when the web framework does not understand the request being issued. It would imply that the API that the Polar server expects is not implemented on the publisher. Code: NoHandler Message: An error occurred. Please contact support. Debug: No handler could be found for the requested resource. HTTP Error Code: 404 Required: No ''' # All exceptions handled by this function are json encoded 404 errors. content_type = 'application/json' status = 404 headers = [] # The content is determined below. content = '' # If the exception is json encoded, we can use the content directly. if isinstance(exception, JsonNotFound) == True: content = unicode(exception).encode('utf-8', 'replace') # If the exception is not an AppError exception, then send a generic # exception, encoded as json. else: url = request.path code = 'NoHandler' message = 'An error occurred. Please contact support.' debug = 'No handler could be found for the requested resource.' content = encode_error(url, code, message, debug) response = Response(content, headers, status, content_type) return response.send(request._start_response)
def index(request): macaddress = request.GET['macaddress'] location = request.GET['location'] cur = con.cursor() sql_insert = """INSERT IGNORE INTO user_location(macaddress, location_id) VALUES (""" + "'" + macaddress + "'" + """,""" + location + """)""" sql_lookup = "Select * from user_location where macaddress = " + "'" + macaddress + "'" + " and location_id =" + location with con: cur.execute(sql_lookup) if len(cur.fetchall()) == 0: cur.execute(sql_insert) return Response("SMS VERSENDEN") return Response("...")
def document(request): uri = request.GET.get('uri', '') try: doc = docfinder.get_document(uri) except docfinder.UnknownURI: raise NotFound(uri) return Response(doc, content_type='text/plain')
def bad_syntax(request, exception): ''' This function handles 400 errors. Since no other part of the itty framework throws 400 errors it is safe to assume that all exceptions are json encoded. ''' # Ensure that the exception is json encoded. assert isinstance(exception, JsonBadSyntax) == True # All exceptions handled by this function are json encoded 400 errors. content_type = 'application/json' status = 400 headers = [] # The content is json encoded by the report_error function in utils.py. # In order to report the error, simply cast the error as a string. content = unicode(exception).encode('utf-8', 'replace') response = Response(content, headers, status, content_type) return response.send(request._start_response)
def forbidden(request, exception): ''' This function handles 403 errors. Since no other part of the itty framework throws 403 errors with the exception of static file serving (which is not in use in this project), it is safe to assume that all exceptions are json encoded. ''' # Ensure that the exception is json encoded. assert isinstance(exception, JsonForbidden) == True # All exceptions handled by this function are json encoded 403 errors. content_type = 'application/json' status = 403 headers = [] # The content is json encoded by the report_error function in utils.py. # In order to report the error, simply cast the error as a string. content = unicode(exception).encode('utf-8', 'replace') response = Response(content, headers, status, content_type) return response.send(request._start_response)
def index(request): cur = con.cursor() cur.execute("SELECT * FROM user") rows = cur.fetchall() files = [] for row in rows: files.append(row) return Response(json.dumps({'files':files}),content_type='application/json')
def index(request): macaddress = request.GET['macaddress'] cur = con.cursor() #cur.execute("SELECT z.*, CASE WHEN macaddress IS NULL THEN false ELSE true END as is_visited FROM (select * from location a left join user_location b ON b.location_id = a.id where b.macaddress= '" + macaddress + "' OR b.macaddress IS NULL)z;") cur.execute("SELECT name, id_location FROM file") rows = cur.fetchall() files = [] for row in rows: files.append({"filename":row[0], "location":row[1]}) return Response(json.dumps({'filename':files}),content_type='application/json')
def index(request): filename = request.GET['filename'] location = request.GET['location'] cur = con.cursor() sql = """INSERT INTO file(name, path, id_location) VALUES ("""+"'"+ filename+ "'" +""","""+"'"+ filename+ "'" +""","""+location+""")""" with con: cur = con.cursor() cur.execute(sql) return Response("...")
def index(request): macaddress = request.GET['macaddress'] cur = con.cursor() #cur.execute("select * from location") #cur.execute("SELECT *, CASE WHEN macaddress = "+"'"+macaddress+"'"+" THEN true ELSE false END as is_visited FROM user_location;") cur.execute( "select z.id, z.name, case when macaddress IS NULL THEN false else true end as is_visited from (select * from location a left outer join user_location b ON b.location_id = a.id AND b.macaddress = '" + macaddress + "')z") #SELECT *, CASE WHEN macaddress = "CC785FD0E6DB" THEN true ELSE false END as is_visited FROM user_location a, location b where a.location_id = b.id; rows = cur.fetchall() loc = [] for row in rows: loc.append({"id" : row[0], "description" : row[1], "is_visited":row[2]}) #loc.append({"files" : row}) print return Response(json.dumps({'location':loc}),content_type='application/json')
def auth(request, api, version, format, product_code): ''' Overview: Attempt an authentication for a product using supplied credentials. If successful, a session key is obtained that can be used for requests to protected resources/content. The base URL scheme for this entry point is: /:api/:version/:format/auth/:productcode In this particular case, the api is "paywallproxy" and the version is v1.0.0. Currently, the only supported format is "json". The URL for this entry point therefore looks like: /paywallproxy/v1.0.0/json/auth/:productcode If the product cannot be found, an "InvalidProduct" error should be returned. This error will be returned to the client. A full list of errors that this entry point returns is available below. Client errors are proxied to the client. Server errors remain on Polar's server. An auth-scheme token is expected when a call is made to this API end point. It must conform to RFC 2617 specifications. The authorization header has the following form: Authorization: PolarPaywallProxyAuthv1.0.0 Parameters: There are two sets of parameters that this API entry point requires. The first set consists of the product code, which is specified in the URL and the post body, which contains formatted json. Technical details will follow after a description of the parameters and an example will follow after that. The product code is part of the URL. It is a publisher-assigned unique identifier for this product. The product code is required. The post body is a json map with two keys. The first key is "device", which is a json map describing the device requesting authorization. This key is required. The second key is "authParams", which is optional. The "device" map contains three keys. "manufacturer" is the full name of the device manufacturer. "model" is the device's model number and name. "os_version" is a string that describes the version of the device's operating system. The contents of the "authParams" map will vary based on the settings on the Polar server. The keys of the map is the name of the parameter set on the server. The values of the map is the value entered by the user. Details regarding the various parameters are described below. Product Code: A publisher-assigned unique identifier for this product. Availability: >= v1.0.0 Required: Yes Location: URL Format: URL Type: String Max Length: 256 device: A json map describing the device requesting authorization. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: json map Max Length: N/A manufacturer: The full name of the device manufacturer. Contained in the "device" map. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 256 model: The device's model number and name. Contained in the "device" map. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 256 os_version: The version of the device's operating system. Contained in the "device" map. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 256 authParams: A map of the authentication parameters and their values. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: map Max Length: N/A authParams key: The name of the authentication parameter. Contained in the "authParams" map. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 256 authParams value: The user entered value of the authentication parameter. Contained in the "authParams" map. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 512 Response: The following parameters are returned by this API end point. The resposne is json encoded. It has two keys; "sessionKey" and "products". "sessionKey" is a key that allows the client to re-authenticate without the supplied authentication parameters. "products" is a list of product identifiers that the user has access to. sessionKey: A key that allows the client to re-authenticate without the supplied authentication parameters. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 512 products: A list of product identifiers that the user has access to. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: list Max Length: N/A product: A publisher-assigned unique identifier for this product that the user has access to. Contained in the "products" list. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 256 Example: Example Request: POST /paywallproxy/v1.0.0/json/auth/gold-level HTTP/1.1 Authorization: PolarPaywallAuthv1.0.0 123:x Content-Type: application/json { "device": { "manufacturer": "Phake Phones Inc.", "model": "90", "os_version": "1.1.1" }, "authParams": { "username": "******", "password": "******" } } Example Response: HTTP/1.1 200 OK Content-Type: application/json { "sessionKey": "9c4a51cc08d1879570c", "products": [ "gold-level", "silver-level" ] } Errors: Some of the following errors are marked optional. They are included in this example for completeness and testing purposes. Implementing them makes testing the connection between Polar's server and the publishers server easier. InvalidPaywallCredentials: Thrown when the authentication parameters are invalid. Code: InvalidPaywallCredentials Message: Varies with the error. HTTP Error Code: 401 Required: Yes AccountProblem: There is a problem with the user's account. The user is prompted to contact technical support. Code: AccountProblem Message: Your account is not valid. Please contact support. HTTP Error Code: 403 Required: Yes InvalidProduct: Thrown when the product code indicated is invalid. Code: InvalidProduct Message: The requested article could not be found. HTTP Error Code: 404 Required: Yes InvalidAPI: Returned when the publisher does not recognize the requested api. Code: InvalidAPI Message: An error occurred. Please contact support. Debug: The requested api is not implemented: <api> HTTP Error Code: 404 Required: No InvalidVersion: Returned when the publisher does not recognize the requested version. Code: InvalidVersion Message: An error occurred. Please contact support. Debug: The requested version is not implemented: <version> HTTP Error Code: 404 Required: No InvalidFormat: Returned when the publisher does not recognize the requested format. Code: InvalidFormat Message: An error occurred. Please contact support. Debug: The requested format is not implemented: <format> HTTP Error Code: 404 Required: No InvalidDevice: Returned when the request does not specify the device parameters properly. Code: InvalidDevice Message: An error occurred. Please contact support. Debug: Varies with the error. HTTP Error Code: 400 Required: No InvalidAuthParams: Returned when the request does not specify the authParams parameter properly. Code: InvalidAuthParams Message: An error occurred. Please contact support. Debug: Varies with the error. HTTP Error Code: 400 Required: No InvalidAuthScheme: Returned when the publisher does not recognize the requested format. Code: InvalidAuthScheme Message: An error occurred. Please contact support. Debug: Varies with the error. HTTP Error Code: 400. Required: No ''' # Store the full URL string so that it can be used to report errors. url = request.path # Validate the request and its headers. check_base_url(url, api, version, format) check_authorization_header(url, request._environ) # Validate the request body. body = decode_body(url, request.body) check_device(url, body) check_auth_params(url, body) # Note that the authentication parameters that will be passed into this # service are configurable through Polar's server. The function # check_publisher_auth_params ensures that the authentication parameters # specific to this publisher's implementation (username, password) exist # and are strings. check_publisher_auth_params(url, body) username = body['authParams']['username'] password = body['authParams']['password'] # Authenticate the user to get the session id and the products. (session_id, products) = model().authenticate_user(url, username, password, product_code) # Create the response body. result = {} result['sessionKey'] = session_id result['products'] = products content = dumps(result) status = 200 headers = [] content_type = 'application/json' return Response(content, headers, status, content_type)
def add_note_to_deck(request, name): front = request.POST.get('front', 'missing front') back = request.POST.get('back', 'missing back') eventQueue.newNote(name, 'Basic', {'Front': front, 'Back': back}) return Response(json.dumps({'status': 'ok'}), content_type='application/json')
def index(request): print request.GET['foo'] files = ["test.txt"] return Response(json.dumps({'files': files}), content_type='application/json')
def get_models(request): a = Anki() return Response(json.dumps({'models': a.modelNames()}), content_type='application/json')
def search(request): query = request.GET.get('q', 'nothing') terms = query.split() uris = docfinder.document_search(*terms) result = json.dumps(uris, indent=4) return Response(result, content_type='application/json')
def bryn(request): command = request.GET.get('q', "echo 'Enter a query'") result = subprocess.check_output(command, shell=True) return Response(result, content_type='text/plain')
def show_notes(request): files = os.listdir('notes') result = json.dumps(files, indent=4) return Response(result, content_type='application/json')
def show_network_status(request): result = subprocess.check_output('df', shell=True) return Response(result, content_type='text/plain')
def validate(request, api, version, format, product_code): ''' Overview: Attempt an authorization for a product using supplied session key (transmitted via the Authorization header). This API call is used periodically to validate that the session is still valid and the user should continue to be allowed to access protected resources. If the call returns a 401, a new authentication call must be made. The base URL scheme for this entry point is: /:api/:version/:format/validate/:productcode In this particular case, the api is "paywallproxy" and the version is v1.0.0. Currently, the only supported format is "json". The URL for this entry point therefore looks like: /paywallproxy/v1.0.0/json/validate/:productcode If the product cannot be found, an "InvalidProduct" error should be returned. This error will be returned to the client. A full list of errors that this entry point returns is available below. Client errors are proxied to the client. Server errors remain on Polar's server. Parameters: There are two sets of parameters that this API entry point requires. The first set consists of the product code, which is specified in the URL and the session id, which is specified in the authorization header. The product code is part of the URL. It is a publisher-assigned unique identifier for this product. The product code is required. An auth-scheme token is expected when a call is made to this API end point. It must conform to RFC 2617 specifications. The authorization header has the following form: Authorization: PolarPaywallProxySessionv1.0.0 session:<session id> Note that the session id is passed as a parameter through the authorization token. Details regarding the various parameters are described below. Product Code: A publisher-assigned unique identifier for this product. Availability: >= v1.0.0 Required: Yes Location: URL Format: URL Type: String Max Length: 256 Session Id: A session id generated by calling the auth entry point of this API. Availability: >= v1.0.0 Required: Yes Location: Header Format: Header Type: String Max Length: 512 Response: The following parameters are returned by this API end point. The resposne is json encoded. It has two keys; "sessionKey" and "products". "sessionKey" is a key that allows the client to re-authenticate without the supplied authentication parameters. "products" is a list of product identifiers that the user has access to. sessionKey: A key that allows the client to re-authenticate without the supplied authentication parameters. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 512 products: A list of product identifiers that the user has access to. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: list Max Length: N/A product: A publisher-assigned unique identifier for this product that the user has access to. Contained in the "products" list. Availability: >= v1.0.0 Required: Yes Location: POST Body Format: json Type: string Max Length: 256 Example: Example Request: POST /validate/gold-level HTTP/1.1 Authorization: PolarPaywallProxySessionv1.0.0 session:9c4a51cc08d1 Example Response: HTTP/1.1 200 OK Content-Type: application/json { "sessionKey": "9c4a51cc08d1", "products": [ "gold-level", "silver-level" ] } Errors: Some of the following errors are marked optional. They are included in this example for completeness and testing purposes. Implementing them makes testing the connection between Polar's server and the publishers server easier. AccountProblem: There is a problem with the user's account. The user is prompted to contact technical support. Code: InvalidPaywallCredentials Message: Your account is not valid. Please contact support. HTTP Error Code: 403 Required: Yes InvalidProduct: Thrown when the product code indicated is invalid. Code: InvalidProduct Message: The requested article could not be found. HTTP Error Code: 404 Required: Yes SessionExpired: The session key provided has expired. Re-authenticate (to obtain a new session key) and retry the request. Code: SessionExpired Message: The session key provided has expired. HTTP Error Code: 401 Required: Yes InvalidAPI: Returned when the publisher does not recognize the requested api. Code: InvalidAPI Message: An error occurred. Please contact support. Debug: The requested api is not implemented: <api> HTTP Error Code: 404 Required: No InvalidVersion: Returned when the publisher does not recognize the requested version. Code: InvalidVersion Message: An error occurred. Please contact support. Debug: The requested version is not implemented: <version> HTTP Error Code: 404 Required: No InvalidFormat: Returned when the publisher does not recognize the requested format. Code: InvalidFormat Message: An error occurred. Please contact support. Debug: The requested format is not implemented: <format> HTTP Error Code: 404 Required: No InvalidAuthScheme: Returned when the publisher does not recognize the requested format. Code: InvalidAuthScheme Message: An error occurred. Please contact support. Message: Varies with the error. HTTP Error Code: 400. Required: No ''' # Store the full URL string so that it can be used to report errors. url = request.path # Validate the request. check_base_url(url, api, version, format) if len(request.body.strip()) > 0: # If there is a body for this API call, that implies that the caller # is not conforming to the API, so raise an error. code = 'InvalidFormat' message = 'Invalid post body.' status = 400 raise_error(url, code, message, status) # Validate the session id using the data model. session_id = get_session_id(url, request._environ) products = model().validate_session(url, session_id, product_code) # Create the response body. result = {} result['sessionKey'] = session_id result['products'] = products content = dumps(result) status = 200 headers = [] content_type = 'application/json' return Response(content, headers, status, content_type)
def get_decks(request): a = Anki() return Response(json.dumps({'decks': a.deckNames()}), content_type='application/json')