[![HUG](https://raw.github.com/timothycrosley/hug/develop/artwork/logo.png)](http://hug.rest)
===================
[![PyPI version](https://badge.fury.io/py/hug.svg)](http://badge.fury.io/py/hug)
[![Build Status](https://travis-ci.org/timothycrosley/hug.svg?branch=master)](https://travis-ci.org/timothycrosley/hug)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/0h7ynsqrbaxs7hfm/branch/master?svg=true)](https://ci.appveyor.com/project/TimothyCrosley/hug)
[![Coverage Status](https://coveralls.io/repos/timothycrosley/hug/badge.svg?branch=master&service=github)](https://coveralls.io/github/timothycrosley/hug?branch=master)
[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://pypi.python.org/pypi/hug/)
[![Join the chat at https://gitter.im/timothycrosley/hug](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/timothycrosley/hug?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
NOTE: For more in-depth documentation visit [hug's website](http://www.hug.rest)
hug aims to make developing Python driven APIs as simple as possible, but no simpler. As a result, it drastically simplifies Python API development.
hug's Design Objectives:
- Make developing a Python driven API as succinct as a written definition.
- The framework should encourage code that self-documents.
- It should be fast. A developer should never feel the need to look somewhere else for performance reasons.
- Writing tests for APIs written on-top of hug should be easy and intuitive.
- Magic done once, in an API framework, is better than pushing the problem set to the user of the API framework.
- Be the basis for next generation Python APIs, embracing the latest technology.
As a result of these goals, hug is Python 3+ only and built upon [Falcon's](https://github.com/falconry/falcon) high performance HTTP library
[![HUG Hello World Example](https://raw.github.com/timothycrosley/hug/develop/artwork/example.gif)](https://github.com/timothycrosley/hug/blob/develop/examples/hello_world.py)
Installing hug
===================
Installing hug is as simple as:
```bash
pip3 install hug --upgrade
```
Ideally, within a [virtual environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/).
Getting Started
===================
Build an example API with a simple endpoint in just a few lines.
```py
# filename: happy_birthday.py
"""A basic (single function) API written using hug"""
import hug
@hug.get('/happy_birthday')
def happy_birthday(name, age:hug.types.number=1):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
```
To run, from the command line type:
```bash
hug -f happy_birthday.py
```
You can access the example in your browser at:
`localhost:8000/happy_birthday?name=hug&age=1`. Then check out the
documentation for your API at `localhost:8000/documentation`
Parameters can also be encoded in the URL (check
out [`happy_birthday.py`](examples/happy_birthday.py) for the whole
example).
```py
@hug.get('/greet/{event}')
def greet(event: str):
"""Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) """
greetings = "Happy"
if event == "Christmas":
greetings = "Merry"
if event == "Kwanzaa":
greetings = "Joyous"
if event == "wishes":
greetings = "Warm"
return "{greetings} {event}!".format(**locals())
```
Which, once you are running the server as above, you can use this way:
```
curl http://localhost:8000/greet/wishes
"Warm wishes!"
```
Versioning with hug
===================
```py
# filename: versioning_example.py
"""A simple example of a hug API call with versioning"""
import hug
@hug.get('/echo', versions=1)
def echo(text):
return text
@hug.get('/echo', versions=range(2, 5))
def echo(text):
return "Echo: {text}".format(**locals())
```
To run the example:
```bash
hug -f versioning_example.py
```
Then you can access the example from `localhost:8000/v1/echo?text=Hi` / `localhost:8000/v2/echo?text=Hi` Or access the documentation for your API from `localhost:8000`
Note: versioning in hug automatically supports both the version header as well as direct URL based specification.
Testing hug APIs
===================
hug's `http` method decorators don't modify your original functions. This makes testing hug APIs as simple as testing any other Python functions. Additionally, this means interacting with your API functions in other Python code is as straight forward as calling Python only API functions. hug makes it easy to test the full Python stack of your API by using the `hug.test` module:
```python
import hug
import happy_birthday
hug.test.get(happy_birthday, 'happy_birthday', {'name': 'Timothy', 'age': 25}) # Returns a Response object
```
You can use this `Response` object for test assertions (check
out [`test_happy_birthday.py`](examples/test_happy_birthday.py) ):
```python
def tests_happy_birthday():
response = hug.test.get(happy_birthday, 'happy_birthday', {'name': 'Timothy', 'age': 25})
assert response.status == HTTP_200
assert response.data is not None
```
Running hug with other WSGI based servers
===================
hug exposes a `__hug_wsgi__` magic method on every API module automatically. Running your hug based API on any standard wsgi server should be as simple as pointing it to `module_name`: `__hug_wsgi__`.
For Example:
```bash
uwsgi --http 0.0.0.0:8000 --wsgi-file examples/hello_world.py --callable __hug_wsgi__
```
To run the hello world hug example API.
Building Blocks of a hug API
===================
When building an API using the hug framework you'll use the following concepts:
**METHOD Decorators** `get`, `post`, `update`, etc HTTP method decorators that expose your Python function as an API while keeping your Python method unchanged
```py
@hug.get() # <- Is the hug METHOD decorator
def hello_world():
return "Hello"
```
hug uses the structure of the function you decorate to automatically generate documentation for users of your API. hug always passes a request, response, and api_version variable to your function if they are defined params in your function definition.
**Type Annotations** functions that optionally are attached to your methods arguments to specify how the argument is validated and converted into a Python type
```py
@hug.get()
def math(number_1:int, number_2:int): #The :int after both arguments is the Type Annotation
return number_1 + number_2
```
Type annotations also feed into `hug`'s automatic documentation
generation to let users of your API know what data to supply.
**Directives** functions that get executed with the request / response data based on being requested as an argument in your api_function.
These apply as input parameters only, and can not be applied currently as output formats or transformations.
```py
@hug.get()
def test_time(hug_timer):
return {'time_taken': float(hug_timer)}
```
Directives may be accessed via an argument with a `hug_` prefix, or by using Python 3 type annotations. The latter is the more modern approach, and is recommended. Directives declared in a module can be accessed by using their fully qualified name as the type annotation (ex: `module.directive_name`).
Aside from the obvious input transformation use case, directives can be used to pipe data into your API functions, even if they are not present in the request query string, POST body, etc. For an example of how to use directives in this way, see the authentication example in the examples folder.
Adding your own directives is straight forward:
```py
@hug.directive()
def square(value=1, **kwargs):
'''Returns passed in parameter multiplied by itself'''
return value * value
@hug.get()
@hug.local()
def tester(value: square=10):
return value
tester() == 100
```
For completeness, here is an example of accessing the directive via the magic name approach:
```py
@hug.di
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
共46个文件
py:28个
md:8个
txt:5个
资源分类:Python库 所属语言:Python 资源全名:hug-2.4.0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源推荐
资源详情
资源评论
收起资源包目录
hug-2.4.0.tar.gz (46个子文件)
hug-2.4.0
MANIFEST.in 28B
PKG-INFO 19KB
ARCHITECTURE.md 11KB
hug.egg-info
PKG-INFO 19KB
requires.txt 23B
SOURCES.txt 758B
entry_points.txt 66B
top_level.txt 4B
dependency_links.txt 1B
CODING_STANDARD.md 1004B
EXTENDING.md 3KB
hug
directives.py 5KB
validate.py 2KB
interface.py 35KB
json_module.py 881B
_empty.py 1KB
route.py 9KB
test.py 4KB
_async.py 2KB
authentication.py 5KB
output_format.py 14KB
types.py 18KB
development_runner.py 5KB
middleware.py 7KB
introspect.py 3KB
format.py 2KB
decorators.py 7KB
__init__.py 3KB
store.py 2KB
use.py 12KB
defaults.py 2KB
transform.py 4KB
redirect.py 2KB
routing.py 22KB
api.py 22KB
_version.py 1KB
input_format.py 3KB
exceptions.py 2KB
LICENSE 1KB
CONTRIBUTING.md 4KB
setup.cfg 187B
FAQ.md 3KB
setup.py 4KB
CHANGELOG.md 18KB
README.md 13KB
ACKNOWLEDGEMENTS.md 2KB
共 46 条
- 1
资源评论
挣扎的蓝藻
- 粉丝: 13w+
- 资源: 15万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功