API¶
Request¶
- class glass.requests.Request(environ=None)[source]¶
This implement HTTP request to access incoming request data.
from glass import request
- args¶
URL query string, values after
?in request path./users/list/?sort=True&type=namesort = request.args.get('sort') type = request.args.get('type') # request.args and request.query are same, use anyone.
- property content_length¶
Request content length
- property content_type¶
Request content_type
- cookies[source]¶
A
dictobject of cookies sent to the server:@app.route('/') def home(): cookie = request.cookies.get('name') do_something(cookie) return 'hello'
- property environ¶
Thread-local property
- files[source]¶
A dict-like object of files posted to the server.:
user_pics = request.files.get('profile_pics') if user_pics: # save the file filename = user_pics.filename user_pics.save_as('/somepath')Note
This only works if the
request.methodis POST, PUT or PATCH, and content_type is multipart/form-data. If not , it returns empty dict object
- get_data()[source]¶
Returns data sent to server as
bytes. It is good to checkcontent_lengthwithrequest.content_lengthbefore calling this method as content_length allows you to know size of the data and to avoid reading a very large data at once.When this method is called, data stream sent to the server will be consumed,
request.postandrequest.fileswill return empty dict if they are called after this method is called.You can read the data sent in small chunck with
request.stream.size = request.content_length if size > 50_000_000: # 50MB # probably, you dont want read data # of this size at once. # use request.stream here
- get_json()[source]¶
Return data sent as json. If content_type is not
application/jsonthis returnsNone
- headers[source]¶
A dict-like object request HTTP Headers Example:
content_type = request.headers.get("Content-Type")
- property host¶
Host field in the request header
- property method¶
HTTP request method
- post[source]¶
A dict-like object of post/put data.
<input type='text' name='username'> <input type='password' name='password'>Get the values with:
request.post.get('username') request.post.get('password')
- query[source]¶
URL query string, values after
?in request path./users/list/?sort=True&type=namesort = request.args.get('sort') type = request.args.get('type') # request.args and request.query are same, use anyone.
- property remote_addr¶
returns client IP address
- property stream¶
Body of the request
# read 1024 bytes from request data data = request.stream.read(1024) # read everything at once data = request.stream.read()
- property user_agent¶
HTTP User-Agent
Response¶
- class glass.response.BaseResponse(content_type='', charset='', status_code=None, headers=None)[source]¶
Base Response class. This class is not returned directly, but it is subclassed by other class. Use subclasess instead.
Use
glass.response.Responseor its subclasses
- Parameters:
content_type – response Content-Type
status_code – response http status code
charset – content-type charset, default utf-8
headers –
dictorlistof tuples, response headers
- delete_cookie(key, **kw)[source]¶
Delete cookie previously sent by the server.
app = GlassApp() @app.route('/') resp = Response('hello') resp.delete_cookie('name',path='/',domain='domain') return resp
- set_cookie(name, value, **kw)[source]¶
Add cookie to the response that will be sent to browser
- Parameters:
name – cookie name
value – cookie value
kw – optional keywords argument
max_age,samesite,domainpath,expires,httponly,secure.Example:
@app.route('/') def home(): resp = Response('hello') resp.set_cookie('name',value) resp.set_cookie('name1',value, max_age=45633,httponly=True, secure=False,samesite='lax') # check mozilla for details about # the keywords argument return resp
- class glass.response.FileResponse(file, *args, **kwargs)[source]¶
Stream file or file object to the browser. Use this class to send file as response Example:
@app.route('/') def send_file(): return FileResponse('/path/to/file.jpg')
- class glass.response.JsonResponse(content, *args, **kwargs)[source]¶
Return json object as response. see
glass.response.BaseResponsefor the parameters and methods@app.route('/') def json() data = {'name':'username','email':'usermail@mail.com'} return JsonResponse(data)
- class glass.response.Redirect(location, *args, content='', **kwargs)[source]¶
Issue redirect response to the browser
- Parameters:
location – redirect location
see
glass.response.BaseResponsefor the parameters and methods
- class glass.response.Response(content, *args, **kwargs)[source]¶
Main response object,
- Parameters:
content –
strorbytesor any object withitersee
glass.response.BaseResponsefor the parametersresp = Response('hello', headers={"key":'value'},status_code=200)
GlassApp¶
- class glass.app.GlassApp(**kwargs)[source]¶
Main application object
from glass import GlassApp app = GlassApp() @app.route('/') def home(): return 'Hello'
- after_request(func)[source]¶
Register a function to run after each request.
This can be used to add header(s) or cookie(s) to the response. The function takes one argument,(
glass.response.Response) and must return the same response object.@app.after_request def set(response): response.set_header('name','value') response.set_cookie('name','value',path='/') return response @app.after_request def turn_upper(response): if isinstance(response.content,(str,bytes)): response.content = response.content.upper() return response
- before_request(func)[source]¶
- Register a function to run before each request.
For example, this can be used to open a database connection, or to load logged in user from session.
@app.before_request def load_user(): id = session.get('user_id') if id: user = db.get(id=id) request.user = user else: # make sure to set request.user = value # to avoid python raising AttributeError request.user = NoneIf the function doest not return None, the return value will be used as the response.
@app.before_request def maintenance(): return "This site is under maintenance"def load_user(): pass app.before_request(load_user)
- error(error)[source]¶
Register a function to call when an error occurs in the application. The function can be registered with code or exception class. The function takes the exception class as argument.
@app.error(404): def not_found(err): return "path not found" # with exception class @app.error(TypeError) def type_error(error): assert error.__class__ is TypeError return 'TypeError exception occurs'
- route(url_rule, methods='GET', view_name=None, **kwargs)[source]¶
Register a view function for URL as decorator
@app.route('/') def index(): return 'Hello'
- run(host='127.0.0.1', port=8000, debug=None, auto_reload=False)[source]¶
Run the application development server.
- Parameters:
host – ip address to listen on. default to localhost
127.0.0.1port – port for the server to listen. default to
8000auto_reload – enable reloader. reload the server when the app source files change. default to
Falsedebug – run the app in debug mode.
app = GlassApp() @app.route('/') def index(): return "Hello" app.run(debug=True)
- template_env[source]¶
Returns
Environmentinstance.
Session¶
- class glass.sessions.Session(data=None)[source]¶
glass session object.
from glass import session @app.route('/') def home(): session['name'] = 'username'
- clear()[source]¶
Clear current session data.
@app.route('/clear') def clear(): session.clear() return 'hello'
- get(key, default=None)[source]¶
Get session data with its key, returns default if not found. Example:
from glass import session @app.route('/') def home(): name = session.get('name')
- property modified¶
Thread-local property
- pop(key, default=None)[source]¶
Remove item from session data and return the item value.
Example:
@app.route('/popname') def pop(): name = session.pop('name') # if you dont need the value # session.pop('name') return 'hello'
- property session_data¶
Thread-local property
glass.template¶
- class glass.template.main.Environment(cache=None, tags=None, filters=None, loader=None, **options)[source]¶
The main environment for templates. The environment stores tags and filter available to all templates and loader to load templates from diffferent sources.
- Parameters:
cache – an object use to cache compiled templates. default
None(dont cache)tags – dict of custom tags.
loader – template loader class to load templates.
filters – dict of custom filters.
- filter(name)[source]¶
Decorator to register custom filter
@env.filter('upper') def upper(value): return value.upper()
- from_string(string)[source]¶
Gets template to render from string, Returns
Template>>> env = Environment() >>> template = env.from_string('hello {{user}}') >>> template.render({'user':'Horlar'})
- get_template(template_name)[source]¶
Gets template to render from file. Returns
Template.>>> env = Environment() >>> template = env.get_template('index.html') >>> template.render({})
- class glass.template.main.FileLoader(path=None)[source]¶
Template loader class to load templates from FileSystem(directory). The argument can be a directory or list of directories
>>> loader = FileLoader('/path/to/templates') >>> # load templates from multiple directories >>> loader = FileLoader(['/path/to/templates','/path/to/other/templates']) >>> env = Environment(loader=loader)
- class glass.template.main.Template(source, env=None)[source]¶
Main template. Use
Environmentinstead of this.
- Parameters:
source – template source
template =Template('Hello {{user}}') template.render({'user':'Horlar'})
url_for¶
- glass.routing.url_for(view_name, **kwargs)[source]¶
Build url for a view
@app.route('/u/login') def login(): return "Hello" # url_for('login')
- Parameters:
view_name – name of the url view
- Required arguments.
arguments for the target url.
/u/<id>/<username>/url_for(‘view’,id=58,username=’user’)Optional arguments. Note, optional arguments start with
_
- Parameters:
_scheme –
url scheme (
http,httpsor other)if not given, scheme is determined in this order.
1 . from app configuration, app.config[‘SERVER_NAME’] =
'http://domain.com'
default to ‘http’.
_fragment – value after
#in urlhttp://domai.com/a/a#target. default to ‘’,no fragment._target – same as
_fragmentOther arguments provided will be used as query string for the url.
path = url_for('login',q="1",x="2",y="3")`` # /u/login?q=1&x=2&y=3New in version 0.0.3.