Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
75 lines (65 sloc) 2.42 KB
from sanic import Sanic
from sanic import response
import aiohttp
import asyncio
import re
import json
app = Sanic(__name__)
INDEX = """<!DOCTYPE html>
<p>JSON (and JSON-P) API for running a HEAD request against a URL.
<li><a href="/?url=">/?url=</a>
<li><a href="/?url=;callback=foo">/?url=;callback=foo</a>
<li><a href="/?url=;url=">/?url=;url=</a>
<p>Background: <a href="">Deploying an asynchronous Python microservice with Sanic and Zeit Now</a></p>
<p>Source code: <a href=""></a></p>
callback_re = re.compile(r'^[a-zA-Z_](\.?[a-zA-Z0-9_]+)+$')
is_valid_callback = callback_re.match
async def head(session, url):
async with session.head(url) as response:
return {
'ok': True,
'headers': dict(response.headers),
'status': response.status,
'url': url,
except Exception as e:
return {
'ok': False,
'error': str(e),
'url': url,
async def handle_request(request):
urls = request.args.getlist('url')
callback = request.args.get('callback')
if urls:
if len(urls) > 10:
return response.json([{
'ok': False,
'error': 'Max 10 URLs allowed'
}], status=400)
async with aiohttp.ClientSession() as session:
head_infos = await asyncio.gather(*[
head(session, url) for url in urls
if callback and is_valid_callback(callback):
return response.text(
'{}({})'.format(callback, json.dumps(head_infos, indent=2)),
headers={'Access-Control-Allow-Origin': '*'},
return response.json(
headers={'Access-Control-Allow-Origin': '*'},
return response.html(INDEX)
if __name__ == '__main__':"", port=8006)
You can’t perform that action at this time.