Annotate debug.py, initial_password.py, narrow.py, response.py.

Also, fixed up the annotations for tornadoviews to better align with
how narrows was defined as `Iterable[Sequence[str]]` rather than
`List[Tuple[str, str]]`.
This commit is contained in:
Max
2016-06-04 11:38:42 -07:00
committed by Tim Abbott
parent 7b2db95d02
commit 04e2745136
7 changed files with 38 additions and 5 deletions

View File

@@ -3,10 +3,12 @@ import codecs
import hashlib import hashlib
import hmac import hmac
from six import text_type
# Encodes the provided URL using the same algorithm used by the camo # Encodes the provided URL using the same algorithm used by the camo
# caching https image proxy # caching https image proxy
def get_camo_url(url): def get_camo_url(url):
# type: (str) -> str # type: (text_type) -> text_type
# Only encode the url if Camo is enabled # Only encode the url if Camo is enabled
if settings.CAMO_URI == '': if settings.CAMO_URI == '':
return url return url

View File

@@ -4,12 +4,17 @@ import code
import traceback import traceback
import signal import signal
from types import FrameType
from typing import Optional
# Interactive debugging code from # Interactive debugging code from
# http://stackoverflow.com/questions/132058/showing-the-stack-trace-from-a-running-python-application # http://stackoverflow.com/questions/132058/showing-the-stack-trace-from-a-running-python-application
# (that link also points to code for an interactive remote debugger # (that link also points to code for an interactive remote debugger
# setup, which we might want if we move Tornado to run in a daemon # setup, which we might want if we move Tornado to run in a daemon
# rather than via screen). # rather than via screen).
def interactive_debug(sig, frame): def interactive_debug(sig, frame):
# type: (int, Optional[FrameType]) -> None
"""Interrupt running process, and provide a python prompt for """Interrupt running process, and provide a python prompt for
interactive debugging.""" interactive debugging."""
d = {'_frame': frame} # Allow access to frame object. d = {'_frame': frame} # Allow access to frame object.
@@ -24,5 +29,6 @@ def interactive_debug(sig, frame):
# SIGUSR1 => Just print the stack # SIGUSR1 => Just print the stack
# SIGUSR2 => Print stack + open interactive debugging shell # SIGUSR2 => Print stack + open interactive debugging shell
def interactive_debug_listen(): def interactive_debug_listen():
# type: () -> None
signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack)) signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack))
signal.signal(signal.SIGUSR2, interactive_debug) signal.signal(signal.SIGUSR2, interactive_debug)

View File

@@ -5,7 +5,12 @@ from django.conf import settings
import hashlib import hashlib
import base64 import base64
from typing import Optional
from six import text_type
def initial_password(email): def initial_password(email):
# type: (text_type) -> Optional[text_type]
"""Given an email address, returns the initial password for that account, as """Given an email address, returns the initial password for that account, as
created by populate_db.""" created by populate_db."""

View File

@@ -1,14 +1,19 @@
from zerver.lib.request import JsonableError from zerver.lib.request import JsonableError
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from typing import Iterable, Sequence, Callable, Dict
from six import text_type
def check_supported_events_narrow_filter(narrow): def check_supported_events_narrow_filter(narrow):
# type: (Iterable[Sequence[text_type]]) -> None
for element in narrow: for element in narrow:
operator = element[0] operator = element[0]
if operator not in ["stream", "topic", "sender", "is"]: if operator not in ["stream", "topic", "sender", "is"]:
raise JsonableError(_("Operator %s not supported.") % (operator,)) raise JsonableError(_("Operator %s not supported.") % (operator,))
def build_narrow_filter(narrow): def build_narrow_filter(narrow):
# type: (Iterable[Sequence[text_type]]) -> Callable[[Dict[text_type, text_type]], bool]
check_supported_events_narrow_filter(narrow) check_supported_events_narrow_filter(narrow)
def narrow_filter(event): def narrow_filter(event):
message = event["message"] message = event["message"]

View File

@@ -3,20 +3,27 @@ from __future__ import absolute_import
from django.http import HttpResponse, HttpResponseNotAllowed from django.http import HttpResponse, HttpResponseNotAllowed
import ujson import ujson
from typing import Optional, Any, Dict, List
from six import text_type
class HttpResponseUnauthorized(HttpResponse): class HttpResponseUnauthorized(HttpResponse):
status_code = 401 status_code = 401
def __init__(self, realm): def __init__(self, realm):
# type (text_type) -> None
HttpResponse.__init__(self) HttpResponse.__init__(self)
self["WWW-Authenticate"] = 'Basic realm="%s"' % (realm,) self["WWW-Authenticate"] = 'Basic realm="%s"' % (realm,)
def json_unauthorized(message): def json_unauthorized(message):
# type: (text_type) -> text_type
resp = HttpResponseUnauthorized("zulip") resp = HttpResponseUnauthorized("zulip")
resp.content = ujson.dumps({"result": "error", resp.content = ujson.dumps({"result": "error",
"msg": message}) + "\n" "msg": message}) + "\n"
return resp return resp
def json_method_not_allowed(methods): def json_method_not_allowed(methods):
# type: (List[text_type]) -> text_type
resp = HttpResponseNotAllowed(methods) resp = HttpResponseNotAllowed(methods)
resp.content = ujson.dumps({"result": "error", resp.content = ujson.dumps({"result": "error",
"msg": "Method Not Allowed", "msg": "Method Not Allowed",
@@ -24,6 +31,7 @@ def json_method_not_allowed(methods):
return resp return resp
def json_response(res_type="success", msg="", data=None, status=200): def json_response(res_type="success", msg="", data=None, status=200):
# type: (text_type, text_type, Optional[Dict[str, Any]], int) -> HttpResponse
content = {"result": res_type, "msg": msg} content = {"result": res_type, "msg": msg}
if data is not None: if data is not None:
content.update(data) content.update(data)
@@ -31,10 +39,13 @@ def json_response(res_type="success", msg="", data=None, status=200):
content_type='application/json', status=status) content_type='application/json', status=status)
def json_success(data=None): def json_success(data=None):
# type: (Optional[Dict[str, Any]]) -> HttpResponse
return json_response(data=data) return json_response(data=data)
def json_error(msg, data=None, status=400): def json_error(msg, data=None, status=400):
# type: (str, Optional[Dict[str, Any]], int) -> HttpResponse
return json_response(res_type="error", msg=msg, data=data, status=status) return json_response(res_type="error", msg=msg, data=data, status=status)
def json_unhandled_exception(): def json_unhandled_exception():
# type: () -> HttpResponse
return json_response(res_type="error", msg="Internal server error", status=500) return json_response(res_type="error", msg="Internal server error", status=500)

View File

@@ -4,9 +4,11 @@ from django.contrib.auth import SESSION_KEY, get_user_model
from django.contrib.sessions.models import Session from django.contrib.sessions.models import Session
from typing import Dict, Optional from typing import Dict, Optional
from six import text_type
def get_session_dict_user(session_dict): def get_session_dict_user(session_dict):
# type: (Dict[str, int]) -> Optional[int] # type: (Dict[text_type, int]) -> Optional[int]
# Compare django.contrib.auth._get_user_session_key # Compare django.contrib.auth._get_user_session_key
try: try:
return get_user_model()._meta.pk.to_python(session_dict[SESSION_KEY]) return get_user_model()._meta.pk.to_python(session_dict[SESSION_KEY])

View File

@@ -4,6 +4,8 @@ from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.http import HttpRequest, HttpResponse from django.http import HttpRequest, HttpResponse
from six import text_type
from zerver.models import get_client, UserProfile, Client from zerver.models import get_client, UserProfile, Client
from zerver.decorator import asynchronous, \ from zerver.decorator import asynchronous, \
@@ -18,7 +20,7 @@ from zerver.lib.event_queue import allocate_client_descriptor, get_client_descri
from zerver.lib.handlers import allocate_handler_id from zerver.lib.handlers import allocate_handler_id
from zerver.lib.narrow import check_supported_events_narrow_filter from zerver.lib.narrow import check_supported_events_narrow_filter
from typing import Union, Optional, Tuple, List, Any from typing import Union, Optional, Iterable, Sequence, List, Any
import time import time
import ujson import ujson
import logging import logging
@@ -34,7 +36,7 @@ def notify(request):
@has_request_variables @has_request_variables
def cleanup_event_queue(request, user_profile, queue_id=REQ()): def cleanup_event_queue(request, user_profile, queue_id=REQ()):
# type: (HttpRequest, UserProfile, str) -> HttpResponse # type: (HttpRequest, UserProfile, text_type) -> HttpResponse
client = get_client_descriptor(queue_id) client = get_client_descriptor(queue_id)
if client is None: if client is None:
return json_error(_("Bad event queue id: %s") % (queue_id,)) return json_error(_("Bad event queue id: %s") % (queue_id,))
@@ -61,7 +63,7 @@ def get_events_backend(request, user_profile, handler,
dont_block = REQ(default=False, validator=check_bool), dont_block = REQ(default=False, validator=check_bool),
narrow = REQ(default=[], validator=check_list(None)), narrow = REQ(default=[], validator=check_list(None)),
lifespan_secs = REQ(default=0, converter=int)): lifespan_secs = REQ(default=0, converter=int)):
# type: (HttpRequest, UserProfile, Any, Optional[Client], Optional[int], Optional[List[str]], bool, bool, Optional[str], bool, List[Tuple[str, str]], int) -> Union[HttpResponse, _RespondAsynchronously] # type: (HttpRequest, UserProfile, Any, Optional[Client], Optional[int], Optional[List[text_type]], bool, bool, Optional[text_type], bool, Iterable[Sequence[text_type]], int) -> Union[HttpResponse, _RespondAsynchronously]
if user_client is None: if user_client is None:
user_client = request.client user_client = request.client