Code Monkey home page Code Monkey logo

itty's Introduction

itty.py

The itty-bitty Python web framework.

itty.py is a little experiment, an attempt at a Sinatra influenced micro-framework that does just enough to be useful and nothing more.

Currently supports:

  • Routing
  • Basic responses
  • Content-types
  • HTTP Status codes
  • URL Parameters
  • Basic GET/POST/PUT/DELETE support
  • User-definable error handlers
  • Redirect support
  • File uploads
  • Header support
  • Static media serving

Beware! If you're looking for a proven, enterprise-ready framework, you're in the wrong place. But it sure is a lot of fun.

Example

from itty import get, run_itty

@get('/')
def index(request):
    return 'Hello World!'

run_itty()

See examples/ for more usages.

Other Sources

A couple of bits have been borrowed from other sources:

Thanks

Thanks go out to Matt Croydon & Christian Metts for putting me up to this late at night. The joking around has become reality. :)

itty's People

Contributors

mcroydon avatar puentesarrin avatar toastdriven avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

itty's Issues

Fix simple typo: registed -> registered

Issue Type

[x] Bug (Typo)

Steps to Replicate

  1. Examine itty.py.
  2. Search for registed.

Expected Behaviour

  1. Should read registered.

Semi-automated issue generated by
https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

To avoid wasting CI processing resources a branch with the fix has been
prepared but a pull request has not yet been created. A pull request fixing
the issue can be prepared from the link below, feel free to create it or
request @timgates42 create the PR. Alternatively if the fix is undesired please
close the issue with a small comment about the reasoning.

https://github.com/timgates42/itty/pull/new/bugfix_typo_registered

Thanks.

Accessing request.POST raises weird error

I have the following code that is used to test out itty, and have encountered this strange exception from the cgi module from the standard library:

<type 'exceptions.TypeError'> occurred on '/': not indexable
Traceback: Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/itty.py", line 603, in handle_request
    response = callback(request, **kwargs)
  File "app.py", line 9, in put_obj
    print(request.POST.get('', ''))
  File "/usr/local/lib/python2.7/site-packages/itty.py", line 157, in __get__
    value = self._function(obj)
  File "/usr/local/lib/python2.7/site-packages/itty.py", line 430, in POST
    return self.build_complex_dict()
  File "/usr/local/lib/python2.7/site-packages/itty.py", line 488, in build_complex_dict
    for field in raw_data:
  File "/usr/local/Cellar/python/2.7.7_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cgi.py", line 517, in __iter__
    return iter(self.keys())
  File "/usr/local/Cellar/python/2.7.7_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cgi.py", line 582, in keys
    raise TypeError, "not indexable"
TypeError: not indexable
127.0.0.1 - - [05/Jun/2014 21:54:46] "POST / HTTP/1.1" 500 17

More context, my code is just trying to print out the dictionary from the post request, i.e.:

@post('/')
def put_obj(request):
    print(request.POST.get('', ''))
    return json.dumps({'ok':True})

minor typo in itty.py

Noticed this while browsing the source. Line 444 should be:

raise RuntimeError("Server '%s' is not a valid server. Please choose a different server." % server)

Response.clear_all_cookies() is broken

It accesses self.request which does not exist.

I propose removal of this method: the iteration would be the responsability of the developer.

@get('/logout')
def logout(request):
    response = Response("...")
    for name in request.cookies:
        response.clear_cookie(name)
    return response

PUT throws error after 1283cb0

decorators were made more performant in 1283cb0, however, the put() function throws an error because the declaration of 'new' local variable was removed. When trying to set new.status on line 430, the error is observed. I put a comment into the commit: 1283cb0#commitcomment-741380 which says my patch is to basically remove line 430 and manually set status in my handlers.

Static file serving on windows, binary vs text

I decided to run my itty based web app on windows today and ran into an issue with serving up images using serve_static_file. It appears that things like images must be served as binary or the browser will not consume it properly.

I've worked up a quick hack for my own purposes however my python foo is weak, and I feel someone with more knowledge should attack this issue...

Hack

def static_file(filename, root=MEDIA_ROOT):
...
...
if content_type(filename).find('text') > -1 or content_type(filename).find('xml') > -1:
  return open(desired_path, 'r').read()

return open(desired_path, 'rb').read()

Python 3 support

Hi,
I've add Python3 support. It's FYI not a pull request because it breaks 2.x compability. Anyway, here's the commit husio@9c81330

remote access?

hello
when i do
python.exe myapp.py i can only access it locally.
How do i access it remotely ?

regards

gevent wsgi deprecated use pywsgi

I think the gevent server adapter must be using pywsgi instead of wsgi as wsgi is now removed and pointed to pywsgi...

from gevent import pywsgi
pywsgi.WSGIServer((host, int(port)), handle_request).serve_forever()

wsgi environ access

To use itty-based applications in a wsgi pipeline with another, itty app should have more access to environ dict.
The most important is a 'SCRIPT_NAME' param, because it is used to construct application urls.
For example, I've implemented it in a ruthenium/itty@23ceba7c445b33fdd110, where I've just added the script_name and user params to request:

self.script_name = self._environ.get('SCRIPT_NAME', '')
self.user = self._environ.get('REMOTE_USER', None)

But maybe the request should have access to the private environ variable using something like 'getenv' or etc?..

itty should output tracebacks to console

Patch against head included:

--- /home/tstromberg/workspace/betterdns/itty.py        2009-04-17 19:26:44.000000000 +0200
+++ ./itty.py   2009-07-03 16:30:07.878876000 +0200
@@ -25,6 +25,7 @@
 import os
 import re
 import sys
+import traceback
 import urlparse
 try:
     from urlparse import parse_qs
@@ -206,7 +207,11 @@
 
 def handle_error(exception, request):
     """If an exception is thrown, deal with it and present an error page."""
-    request._environ['wsgi.errors'].write("Exception occurred on '%s': %s\n" % (request._environ['PATH_INFO'], exception))
+    (e_type, e_value, e_tb) = sys.exc_info()
+    msg = ("%s occurred on '%s': %s\nTraceback: %s" %
+           (exception.__class__, request._environ['PATH_INFO'], exception,
+            ''.join(traceback.format_exception(e_type, e_value, e_tb))))
+    request._environ['wsgi.errors'].write(msg)
     
     if isinstance(exception, RequestError):
         status = getattr(exception, 'status', 404)

Unicode error with python3

I was running a script that imported itty and whenever I run it using python3 I get this error:
Traceback (most recent call last):
File "connect_cisco_bot.py", line 1, in
from itty import post, run_itty
File "/home/ubuntu/.local/lib/python3.5/site-packages/itty.py", line 588
except UnicodeError, e:
^
SyntaxError: invalid syntax

When I run it with python2.7 it works fine.

Returning unicode strings as response causes wsgi error

Traceback (most recent call last):
File "/usr/local/Cellar/python/2.6.2/lib/python2.6/wsgiref/handlers.py", line 94, in run
self.finish_response()
File "/usr/local/Cellar/python/2.6.2/lib/python2.6/wsgiref/handlers.py", line 135, in finish_response
self.write(data)
File "/usr/local/Cellar/python/2.6.2/lib/python2.6/wsgiref/handlers.py", line 210, in write
assert type(data) is StringType,"write() argument must be string"
AssertionError: write() argument must be string
localhost - - [11/Jan/2010 11:02:47] "GET / HTTP/1.1" 500 59

When returning string u'Test?\n'

handle_request doesn't always call handle_error

It's possible to get this error:

Traceback (most recent call last):
File "/usr/lib/python2.6/wsgiref/handlers.py", line 93, in run
self.result = application(self.environ, self.start_response)
File "lib/python2.6/site-packages/itty-0.6.4-py2.6.egg/itty.py", line 227, in handle_request
return handle_error(e, request)

because this code uses 'request' on 227 when it might not be bound yet.

221     try:
222         request = Request(environ, start_response)
223         
224         (re_url, url, callback), kwargs = find_matching_url(request)
225         response = callback(request, **kwargs)
226     except Exception, e:
227         return handle_error(e, request)

I would expect line 222 to be before the try-block, but I also don't know how I made this error. It started happening when I sent a "Content-type: application/json" header with my POST request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.