async def test(request): url = json.loads(request.body)["courseUrl"] if not re.search(regex, url): text = f"Invalid Url : {url}" print(text) return response.text(text) uqcourses = await uq_scraper.main(url) if isinstance(uqcourses, Exception): if isinstance(uqcourses, aiohttp.client.ClientConnectionError): text = f"Invalid Url : {uqcourses}" print(text) return response.text(text) if isinstance(uqcourses, aiohttp.client.InvalidURL): text = f"Invalid Url : {uqcourses}" print(text) return response.text(text) elif isinstance(uqcourses, AttributeError): text = f"Not a uq URL : {url}" print(text) return response.text(text) elif isinstance(uqcourses, InvalidCoursePageError): text = f"Invalid program code : {url}" print(text) return response.text(text) else: text = f"Some unhandled error occurred, Sorry" print(text) return response.text(text) return response.json({"Courses": uqcourses})
def analyse_ptr(domain_ip, mode): ''' Get list of domains whose server IP address is domain_ip :param domain_ip: the input data about domain IP address :param mode: Conditions for Query End. if no new results are added continuous mode DNS query, stop querying. :return: Returns a list of results, each result in the list is a domain name and its type is string ''' para = {} para['domain'] = domain_ip para['type'] = 'ptr' para['mode'] = mode response = requests.get(ANALYSE_PTR_URL, params=para,timeout= PTR_TIMEOUT) try: results = json.loads(response.content) except: raise Exception("Internal Server Error:The server encountered an internal error " "and was unable to complete your request.Either the server is " "overloaded or there is an error in the application.") output = list() # 返回计算结果列表 for result in results['results']: # 对于返回结果列表中的每一个结果 try: for subresult in result['PTR']: # 对result[type]中的每一个子记录 for answer in subresult['answer list']: # 对answer list中的每一个子记录,即真正记录结果的记录 output.append(answer['data']) # 将记录类型和记录结果添加到output列表中 except: continue return output
async def index(request): file_path = "/Users/livehealth/Downloads/imdb.json t.json" file_stat = await async_os.stat(file_path) headers = {"Content-Length": str(file_stat.st_size)} file_content = await file_stream( file_path ) json_file = json.loads(file_content) return json_file
async def action(request): try: # Get action and conversation ts recieved_action = json.loads(request.form['payload'][0])['actions'][0] conversation_ts = recieved_action['action_id'].split('_')[-1] # Fill current conversation user story attributes if recieved_action['type'] != 'button': if recieved_action['type'] == 'static_select': app.sessions_dict[conversation_ts][recieved_action['placeholder']['text']] = \ recieved_action['selected_option']['value'] elif recieved_action['type'] == 'datepicker': app.sessions_dict[conversation_ts][ 'Deadline'] = recieved_action['selected_date'] else: # Create User Story and post link to slack if recieved_action['value'] == 'create': # Get parent request message text params = { 'channel': app.sessions_dict[conversation_ts]['channel'], 'latest': conversation_ts, 'inclusive': 'true', 'limit': 1 } parent_message = requests.get( slack_cfg['api_url'] + '/conversations.history', headers=headers_slack, params=params).json()['messages'][0] app.sessions_dict[conversation_ts][ 'Description'] = parent_message['text'] if 'user' in parent_message: app.sessions_dict[conversation_ts][ 'Requester'] = requests.get( slack_cfg['api_url'] + '/users.info', params={ 'user': parent_message['user'] }, headers=headers_slack).json( )['user']['profile']['display_name_normalized'] elif 'username' in parent_message: app.sessions_dict[conversation_ts][ 'Requester'] = parent_message['username'] else: app.sessions_dict[conversation_ts]['Requester'] = '' if 'attachments' in parent_message: for attachment in parent_message["attachments"]: for field in slack_cfg['attachments_fields']: if field in attachment: app.sessions_dict[conversation_ts][ 'Description'] += '\n' + str( attachment[field]) if 'files' in parent_message: for file in parent_message["files"]: app.sessions_dict[conversation_ts][ 'Description'] += '\n' + '[' + file[ 'title'] + '](' + file['url_private'] + ')' user_story = User_Story(app.sessions_dict[conversation_ts]) logger.info("user_story instance {0}".format( json.dumps(user_story.body, indent=4, sort_keys=True))) user_story_id = targetprocess(resource='UserStories', data=user_story.body, method='post')['Id'] json_data = { 'channel': app.sessions_dict[conversation_ts]['channel'], 'thread_ts': conversation_ts, 'text': "Link: {0}/entity/{1}".format(tp_cfg['url'], user_story_id) } requests.post(slack_cfg['api_url'] + '/chat.postMessage', headers=headers_slack, json=json_data) # Cleanup after canceled or created user story response_url = json.loads( request.form['payload'][0])['response_url'] requests.post(response_url, headers=headers_slack, json={'delete_original': True}) del app.sessions_dict[conversation_ts] return response.json({ 'ok': 'true', 'status': 'Action recieved' }, status=200) except Exception as e: logger.error(e) return response.json( { 'ok': 'false', 'status': 'error', 'error': 'Bad request' }, headers={'X-Slack-No-Retry': 1}, status=400)
async def slack_app(req: Request): if not signature_verifier.is_valid( body=req.body.decode("utf-8"), timestamp=req.headers.get("X-Slack-Request-Timestamp"), signature=req.headers.get("X-Slack-Signature"), ): return HTTPResponse(status=403, body="invalid request") if "command" in req.form and req.form["command"] == "/open-modal": try: enterprise_id = req.form.get("enterprise_id") team_id = req.form["team_id"] bot = installation_store.find_bot( enterprise_id=enterprise_id, team_id=team_id, ) bot_token = bot.bot_token if bot else None if not bot_token: return HTTPResponse(status=200, body="Please install this app first!") client = AsyncWebClient(token=bot_token) await client.views_open( trigger_id=req.form["trigger_id"], view={ "type": "modal", "callback_id": "modal-id", "title": {"type": "plain_text", "text": "Awesome Modal"}, "submit": {"type": "plain_text", "text": "Submit"}, "close": {"type": "plain_text", "text": "Cancel"}, "blocks": [ { "type": "input", "block_id": "b-id", "label": { "type": "plain_text", "text": "Input label", }, "element": { "action_id": "a-id", "type": "plain_text_input", }, } ], }, ) return HTTPResponse(status=200, body="") except SlackApiError as e: code = e.response["error"] return HTTPResponse( status=200, body=f"Failed to open a modal due to {code}" ) elif "payload" in req.form: payload = json.loads(req.form["payload"]) if ( payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id" ): submitted_data = payload["view"]["state"]["values"] print( submitted_data ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return HTTPResponse(status=200, body="") return HTTPResponse(status=404, body="Not found")
from sanic import Sanic from sanic.response import json, html, redirect, file_stream from sanic_session import Session, InMemorySessionInterface from jinja2 import Environment, PackageLoader, select_autoescape, FileSystemLoader import urllib.parse import json import os.path import os with open('config.json', 'r') as configfile: configdata = configfile.read() config = json.loads(configdata) app = Sanic(__name__) app.static('/static', './static') session = Session(app, interface=InMemorySessionInterface()) env = Environment(loader=FileSystemLoader('templates'), autoescape=select_autoescape(['html', 'xml'])) def request_parse(body): return urllib.parse.parse_qs(body.decode('utf-8')) def render_template(template, **kwargs): template = env.get_template(template) return html(template.render(kwargs, url_for=app.url_for)) def get_file_locations(directory):