Commit 1ecc432c authored by Louis's avatar Louis
Browse files

Web server is a submodule: `python -m pypimonitor.httpd`

parent aa85ab72
- [ ] `python -m pypimonitor` write an html file to stdout. It taks as argument a yaml file (see below)
- [ ] `python -m pypimonitor.http --port PORT DIR1 DIR2` launch a web server
- [x] `python -m pypimonitor.http --port PORT DIR1 DIR2` launch a web server
- [ ] - Connection to http://localhost:PORT/foo: render DIR1/foo.yaml as an html page (or DIR2/foo.yaml if not found)
- [ ] - Connection to http://localhost:PORT: same action as now, using pkg=, usr=, and row= arguments. The array is limited to some pypi-only cells
- [ ] Change default port
- [x] Change default port
- [x] Use chart.js (see TODO/chart.html)
- [x] Use it
- [x] Remove outdated methods `iter_*`
......
......@@ -12,6 +12,8 @@ import sys
import urllib
import xmlrpc.client as xmlrpclib
VERSION = "0.2.0-dev"
_client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
class PackageList:
......
from urllib.parse import urlparse, parse_qs
import colorsys
import datetime
import functools
import http.server
import jinja2
import operator
import os
import pkg_resources
import random
import argparse
import logging
import pypimonitor
from pypimonitor import PackageList
from pypimonitor import renderer
class Counter:
def __init__(self):
self.value = 0
def count(self):
self.value += 1
return self.value
def as_id(string):
return "".join(list(filter(str.isalnum, string)))
def random_color(seed, saturation, value):
old_seed = random.random()
random.seed(seed)
rgb = colorsys.hsv_to_rgb(random.random(), saturation, value)
random.seed(old_seed)
return ("#%02x%02x%02x" % tuple([int(value * 255) for value in rgb]))
def _get_environment():
TEMPLATEDIR = os.path.join(
pkg_resources.resource_filename(__name__, 'data'),
'templates',
)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATEDIR))
env.globals['counter'] = Counter().count
env.globals['now'] = datetime.datetime.now()
env.filters['PackageList'] = PackageList
env.filters['datetime'] = operator.methodcaller('strftime', "%Y-%m-%d %H:%M:%S")
env.filters['as_id'] = as_id
env.filters['color'] = random_color
return env
LOGGER = logging.getLogger(pypimonitor.__name__)
DEFAULT_PORT = 8080
DEFAULT_HOST = ""
class HttpHandler(http.server.BaseHTTPRequestHandler):
def render(self, source, **kwargs):
env = _get_environment()
env = renderer._get_environment()
# Check badges
badges = []
for badge in kwargs['badges']:
try:
env.get_template("badges/{}.html".format(badge))
badges.append(badge)
except jinja2.exceptions.TemplateNotFound:
continue
env.get_template("badges/{}.html".format(badge))
badges.append(badge)
kwargs['badges'] = badges
# Render
......@@ -82,8 +46,45 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
badges=querydict.get('badges', ["homepage", "pypi_version", "pypi_mdownload", "pypi_wdownload", "pypi_ddownload"]),
))
def _type_address(text):
partition = text.partition(":")
if not partition[2]:
return partition[0], DEFAULT_PORT
try:
return partition[0], int(partition[2])
except ValueError:
LOGGER.error("Argument '{}' is not a valid port number. Using '{}' instead.".format(partition[2], DEFAULT_PORT))
return partition[0], DEFAULT_PORT
return partition[0], DEFAULT_PORT
def commandline_parser():
"""Return a command line parser."""
parser = argparse.ArgumentParser(
#prog="scal",
description="A year calendar producer.",
)
parser.add_argument(
'--version',
help='Show version',
action='version',
version='%(prog)s ' + pypimonitor.VERSION
)
parser.add_argument(
'-a', '--address',
help='Server address and port, of the form HOST:PORT, HOST, :PORT.',
nargs=1,
type=_type_address,
default=[(DEFAULT_HOST, DEFAULT_PORT)],
)
return parser
if __name__ == "__main__":
server = http.server.HTTPServer(('', 8081), HttpHandler)
arguments = commandline_parser().parse_args()
server = http.server.HTTPServer(arguments.address[0], HttpHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
......
import colorsys
import datetime
import functools
import jinja2
import operator
import os
import pkg_resources
import random
class Counter:
def __init__(self):
self.value = 0
def count(self):
self.value += 1
return self.value
def as_id(string):
return "".join(list(filter(str.isalnum, string)))
def random_color(seed, saturation, value):
old_seed = random.random()
random.seed(seed)
rgb = colorsys.hsv_to_rgb(random.random(), saturation, value)
random.seed(old_seed)
return ("#%02x%02x%02x" % tuple([int(value * 255) for value in rgb]))
def _get_environment():
TEMPLATEDIR = os.path.join(
pkg_resources.resource_filename(__name__, 'data'),
'templates',
)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATEDIR))
env.globals['counter'] = Counter().count
env.globals['now'] = datetime.datetime.now()
env.filters['datetime'] = operator.methodcaller('strftime', "%Y-%m-%d %H:%M:%S")
env.filters['as_id'] = as_id
env.filters['color'] = random_color
return env
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment