gramex.handlers
¶
Handlers set up the micro-services for gramex.services.url.
BaseMixin
¶
Common utilities for all handlers. This is used by BaseHandler and BaseWebSocketHandler.
setup(transform={}, redirect={}, methods=None, auth=None, log=None, set_xsrf=None, error=None, xsrf_cookies=None, cors=None, ratelimit=None, kwargs)
classmethod
¶
One-time setup for all request handlers. This is called only when gramex.yaml is parsed / changed.
Source code in gramex\handlers\basehandler.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
clear_special_keys(kwargs, args)
classmethod
¶
Remove keys handled by BaseHandler that may interfere with setup(). This should be called explicitly in setup() where required.
Source code in gramex\handlers\basehandler.py
102 103 104 105 106 107 108 109 110 111 112 |
|
get_list(val, key='', eg='', caps=True)
classmethod
¶
Split comma-separated values into a set.
Process kwargs that can be a comma-separated string or a list,
like BaseMixin’s methods:
, cors.origins
, cors.methods
, cors.headers
,
ratelimit.keys
, etc.
Examples:
>>> get_list('GET, PUT') == {'GET', 'PUT'}
>>> get_list(['GET', ' ,get '], caps=True) == {'GET'}
>>> get_list([' GET , PUT', ' ,POST, ']) == {'GET', 'PUT', 'POST'}
Parameters:
Name | Type | Description | Default |
---|---|---|---|
val |
Union[list, tuple, str]
|
Input to split. If val is not str/list/tuple, raise |
required |
key |
str
|
|
''
|
eg |
str
|
Example values to display in error message |
''
|
caps |
bool
|
True to convert values to uppercase |
True
|
Returns:
Type | Description |
---|---|
set
|
Unique comma-separated values |
Source code in gramex\handlers\basehandler.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
|
check_http_method()
¶
If method: […] is specified, reject all methods not in the allowed methods set
Source code in gramex\handlers\basehandler.py
158 159 160 161 162 163 164 165 |
|
check_cors()
¶
For simple CORS requests, send Access-Control-Allow-Origin:
Source code in gramex\handlers\basehandler.py
188 189 190 191 192 193 194 195 196 |
|
cors_origin()
¶
Returns the origin to set in Access-Control-Allow-Origin header.
Source code in gramex\handlers\basehandler.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
|
setup_default_kwargs()
classmethod
¶
Use default config from handlers.
Source code in gramex\handlers\basehandler.py
280 281 282 283 284 285 286 287 288 289 290 |
|
setup_session(session_conf)
classmethod
¶
handler.session returns the session object. It is saved on finish.
Source code in gramex\handlers\basehandler.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
|
setup_ratelimit(ratelimit, ratelimit_app_conf)
classmethod
¶
Initialize rate limiting checks
Source code in gramex\handlers\basehandler.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
|
reset_ratelimit(pool, keys, value=0)
classmethod
¶
Reset the rate limit usage for a specific pool.
Examples:
>>> reset_ratelimit('/api', ['2022-01-01', 'x@example.org'])
>>> reset_ratelimit('/api', ['2022-01-01', 'x@example.org'], 10)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pool |
str
|
Rate limit pool to use. This is the url’s |
required |
keys |
List[Any]
|
specific instance to reset. If your |
required |
value |
int
|
sets the usage counter to this number (default: |
0
|
Source code in gramex\handlers\basehandler.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
setup_redirect(redirect)
classmethod
¶
Any handler can have a redirect:
kwarg that looks like this:
redirect:
query: next # If the URL has a ?next=..., redirect to that page next
header: X-Next # Else if the header has an X-Next=... redirect to that
url: ... # Else redirect to this URL
Only these 3 keys are allowed. All are optional, and checked in the order specified. So, for example:
redirect:
header: X-Next # Checks the X-Next header first
query: next # If it's missing, uses the ?next=
You can also specify a string for redirect. redirect: ...
is the same
as redirect: {url: ...}
.
When any BaseHandler subclass calls self.save_redirect_page()
, it
stores the redirect URL in session['_next_url']
. The URL is
calculated relative to the handler’s URL.
After that, when the subclass calls self.redirect_next()
, it
redirects to session['_next_url']
and clears the value. (If the
_next_url
was not stored, we redirect to the home page /
.)
Only some handlers implement redirection. But they all implement it in this same consistent way.
Source code in gramex\handlers\basehandler.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
|
authorize()
¶
BaseMixin assumes every handler has an authorize() function
Source code in gramex\handlers\basehandler.py
599 600 601 |
|
setup_log()
classmethod
¶
Logs access requests to gramex.requests as a CSV file.
Source code in gramex\handlers\basehandler.py
603 604 605 606 607 608 609 610 611 |
|
setup_error(error)
classmethod
¶
Sample configuration:
error:
404:
path: template.json # Use a template
autoescape: false # with no autoescape
whitespace: single # as a single line
headers:
Content-Type: application/json
500:
function: module.fn
args: [=status_code, =kwargs, =handler]
Source code in gramex\handlers\basehandler.py
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 |
|
setup_xsrf(xsrf_cookies)
classmethod
¶
Sample configuration:
xsrf_cookies: false # Disables xsrf_cookies
xsrf_cookies: true # or anything other than false keeps it enabled
Source code in gramex\handlers\basehandler.py
693 694 695 696 697 698 699 700 701 702 703 |
|
xsrf_check_required()
¶
Returns True if the request is (likely) from a browser and needs XSRF check.
This is used to handle XSRF. If the request is NOT from a browser (e.g. server, AJAX), no AJAX checks are required. If any of the following are true, it’s not a browser request.
X-Requested-With: XMLHttpRequest
. XMLHttpRequest sends thisSec-Fetch-Mode: cors
. Fetch sends these
Source code in gramex\handlers\basehandler.py
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 |
|
xsrf_ajax()
¶
Validates XSRF cookies if it’s a browser-request (not AJAX)
Internally, it uses Tornado’s check_xsrf_cookie().
Source code in gramex\handlers\basehandler.py
722 723 724 725 726 727 728 |
|
noop()
¶
Does nothing. Used when overriding functions or providing a dummy operation
Source code in gramex\handlers\basehandler.py
730 731 732 |
|
save_redirect_page()
¶
Loop through all redirect: methods and save the first available redirect
page against the session. Defaults to previously set value, else /
.
See setup_redirect.
Source code in gramex\handlers\basehandler.py
734 735 736 737 738 739 740 741 742 743 744 745 746 |
|
redirect_next()
¶
Redirect the user session['_next_url']
. If it does not exist,
set it up first. Then redirect.
See setup_redirect.
Source code in gramex\handlers\basehandler.py
748 749 750 751 752 753 754 755 756 757 |
|
session
property
¶
By default, session is not implemented. You need to specify a
session:
section in gramex.yaml
to activate it. It is replaced by
the get_session
method as a property.
get_session(expires_days=None, new=False)
¶
Return the session object for the cookie “sid” value. If no “sid” cookie exists, set up a new one. If no session object exists for the sid, create it. By default, the session object contains a “id” holding the “sid” value.
The session is a dict. You must ensure that it is JSON serializable.
Sessions use these pre-defined timing keys (values are timestamps):
_t
is the expiry time of the session_l
is the last time the user accessed a page. Updated by setup_redirect_i
is the inactive expiry duration in seconds, i.e. ifnow > _l + _i
, the session has expired.
new=
creates a new session to avoid session fixation.
https://www.owasp.org/index.php/Session_fixation.
[set_user()
][gramex.handlers.AuthHandler.set_user] uses it.
When the user logs in:
- If no old session exists, it returns a new session object.
- If an old session exists, it creates a new “sid” and new session object, copying all old contents, but updates the “id” and expiry (_t).
Source code in gramex\handlers\basehandler.py
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 |
|
save_session()
¶
Persist the session object as a JSON
Source code in gramex\handlers\basehandler.py
911 912 913 914 |
|
otp(expire=60, user=None, size=None, type='OTP', kwargs)
¶
Return one-time password valid for expire
seconds.
The OTP is used as the X-Gramex-OTP header or in ?gramex-otp=
on any request.
This overrides the user with the passed user
object for that session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expire |
float
|
Time when this token expires, in seconds (e.g. |
60
|
user |
Union[str, dict]
|
User object to store against token. Defaults to current user. Raises HTTP 403 Unauthorized if there’s no user |
None
|
size |
int
|
Length of the OTP in characters. |
None
|
type |
str
|
Identifier for type of OTP. |
'OTP'
|
kwargs |
Dict[str, Any]
|
Additional columns to add (if they exist) |
{}
|
Returns:
Type | Description |
---|---|
str
|
Generated OTP |
Internally, this stores it in storelocations.otp
database in a table with 4+ keys:
token
: Generated OTP withsize
charactersuser
: The passeduser
string or dict, JSON-encodedtype
: The passedtype
string, stored as isexpire
: The expiry time in seconds since epoch- Any additional columns passed in
kwargs
, if they exist
Source code in gramex\handlers\basehandler.py
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 |
|
get_otp(key, revoke=False)
¶
Return the user object given the OTP key. Revoke the OTP if requested.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key |
str
|
OTP to return |
required |
revoke |
bool
|
True to revoke the OTP. False to retain it |
False
|
Returns:
Type | Description |
---|---|
Union[str, dict, None]
|
|
Source code in gramex\handlers\basehandler.py
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 |
|
revoke_otp(key)
¶
Revoke an OTP. Returns the user object from gramex.handlers.BaseMixin.get_otp.
Source code in gramex\handlers\basehandler.py
999 1000 1001 |
|
apikey(expire=1000000000.0, user=None, size=None, kwargs)
¶
Return API Key. Usage is same as gramex.handlers.BaseMixin.otp
The API key is used as the X-Gramex-Key header or in ?gramex-key=
on any request.
This overrides the user with the passed user
object for that session.
Source code in gramex\handlers\basehandler.py
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 |
|
revoke_apikey(key)
¶
Revoke API Key. Returns the user object from gramex.handlers.BaseMixin.get_otp.
Source code in gramex\handlers\basehandler.py
1017 1018 1019 |
|
override_user()
¶
Internal method to override the user.
Use X-Gramex-User
HTTP header to override current user for the session.
Use X-Gramex-OTP
HTTP header to set user based on OTP, or ?gramex-otp=
.
Use X-Gramex-Key
HTTP header to set user based on API key, or ?gramex-key=
.
Source code in gramex\handlers\basehandler.py
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 |
|
set_last_visited()
¶
Update session last visited time if we track inactive expiry.
session._l
is the last time the user accessed a page.session._i
is the seconds of inactivity after which the session expires.- If
session._i
is set (we track inactive expiry), we setsession._l
to now.
Source code in gramex\handlers\basehandler.py
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 |
|
check_ratelimit()
¶
Raise HTTP 429 if usage exceeds rate limit. Set X-Ratelimit-* HTTP headers
Source code in gramex\handlers\basehandler.py
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
update_ratelimit()
¶
If request succeeds, increase rate limit usage count by 1
Source code in gramex\handlers\basehandler.py
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 |
|
get_ratelimit()
¶
Get the rate limit with the least remaining usage for the current request.
If there are multiple rate limits, it picks the one with least remaining usage and returns an AttrDict with these keys:
limit
: the limit on the rate limit (e.g. 3)usage
: the usage so far (BEFORE current request, e.g. 0, 1, 2, 3, …)remaining
: the remaining requests (AFTER current request, e.g. 2, 1, 0, 0, …)expiry
: seconds to expiry for this rate limit
Source code in gramex\handlers\basehandler.py
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 |
|
set_ratelimit_headers()
¶
Sets the headers from the Ratelimit HTTP headers draft.
X-Ratelimit-Limit
is the rate limitX-Ratelimit-Remaining
has the remaining requestsX-Ratelimit-Reset
has seconds after which the rate limit resetsRetry-After
is same as X-Ratelimit-Reset, but is set only if the limit is exceeded
Source code in gramex\handlers\basehandler.py
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 |
|
initialize_handler()
¶
Initialize self.args and other handler attributes
Source code in gramex\handlers\basehandler.py
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 |
|
update_body_args()
¶
Update self.args with JSON body if Content-Type is application/json
Source code in gramex\handlers\basehandler.py
1186 1187 1188 1189 1190 1191 |
|
get_arg(name, default=Ellipsis, first=False)
¶
Returns the value of the argument with the given name. Similar to
.get_argument
but uses self.args
instead.
If default is not provided, the argument is considered to be
required, and we raise a MissingArgumentError
if it is missing.
If the argument is repeated, we return the last value. If first=True
is passed, we return the first value.
self.args
is always UTF-8 decoded unicode. Whitespaces are stripped.
Source code in gramex\handlers\basehandler.py
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 |
|
BaseHandler
¶
BaseHandler provides auth, caching and other services common to all request handlers. All RequestHandlers must inherit from BaseHandler.
get_current_user()
¶
Return the user
key from the session as an AttrDict if it exists.
Source code in gramex\handlers\basehandler.py
1258 1259 1260 1261 |
|
log_exception(typ, value, tb)
¶
Store the exception value for logging
Source code in gramex\handlers\basehandler.py
1263 1264 1265 1266 1267 1268 |
|
argparse(args, kwargs)
¶
Parse URL query parameters and return an AttrDict. For example:
args = handler.argparse('x', 'y')
args.x # is the last value of ?x=value
args.y # is the last value of ?y=value
A missing ?x=
or ?y=
raises a HTTP 400 error mentioning the
missing key.
For optional arguments, use:
args = handler.argparse(z={'default': ''})
args.z # returns '' if ?z= is missing
You can convert the value to a type:
args = handler.argparse(limit={'type': int, 'default': 100})
args.limit # returns ?limit= as an integer
You can restrict the choice of values. If the query parameter is not in choices, we raise a HTTP 400 error mentioning the invalid key & value:
args = handler.argparse(gender={'choices': ['M', 'F']})
args.gender # returns ?gender= which will be 'M' or 'F'
You can retrieve multiple values as a list:
args = handler.argparse(cols={'nargs': '*', 'default': []})
args.cols # returns an array with all ?col= values
type:
conversion and choices:
apply to each value in the list.
To return all arguments as a list, pass list
as the first parameter:
args = handler.argparse(list, 'x', 'y')
args.x # ?x=1 sets args.x to ['1'], not '1'
args.y # Similarly for ?y=1
To handle unicode arguments and return all arguments as str
or
unicode
or bytes
, pass the type as the first parameter:
args = handler.argparse(str, 'x', 'y')
args = handler.argparse(bytes, 'x', 'y')
args = handler.argparse(unicode, 'x', 'y')
By default, all arguments are added as str in PY3 and unicode in PY2.
There are the full list of parameters you can pass to each keyword argument:
- name: Name of the URL query parameter to read. Defaults to the key
- required: Whether or not the query parameter may be omitted
- default: The value produced if the argument is missing. Implies required=False
- nargs: The number of parameters that should be returned. ‘*’ or ‘+’ return all values as a list.
- type: Python type to which the parameter should be converted (e.g.
int
) - choices: A container of the allowable values for the argument (after type conversion)
You can combine all these options. For example:
args = handler.argparse(
'name', # Raise error if ?name= is missing
department={'name': 'dept'}, # ?dept= is mapped to args.department
org={'default': 'Gramener'}, # If ?org= is missing, defaults to Gramener
age={'type': int}, # Convert ?age= to an integer
married={'type': bool}, # Convert ?married to a boolean
alias={'nargs': '*'}, # Convert all ?alias= to a list
gender={'choices': ['M', 'F']}, # Raise error if gender is not M or F
)
Source code in gramex\handlers\basehandler.py
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 |
|
BaseWebSocketHandler
¶
get_current_user()
¶
Return the user
key from the session as an AttrDict if it exists.
Source code in gramex\handlers\basehandler.py
1490 1491 1492 1493 |
|
authorize()
¶
If a valid user isn’t logged in, send a message and close connection
Source code in gramex\handlers\basehandler.py
1495 1496 1497 1498 1499 1500 1501 1502 |
|
CaptureHandler
¶
Renders a web page as a PDF or as an image. It accepts the same arguments as
Capture
.
The page is called with the same args as Capture.capture()
. It also
accepts a ?start
parameter that restarts capture.js if required.
ComicHandler
¶
DirectoryHandler = FileHandler
module-attribute
¶
DriveHandler
¶
Lets users manage files. Here’s a typical configuration
path: $GRAMEXDATA/apps/appname/ # Save files here
user_fields: [id, role, hd] # user attributes to store
tags: [tag] # <input name=""> to store
allow: [.doc, .docx] # Only allow these files
ignore: [.pdf] # Don't allow these files
max_file_size: 100000 # Files must be smaller than this
redirect: # After uploading the file,
query: next # ... redirect to ?next=
url: /$YAMLURL/ # ... else to this directory
File metadata is stored in
post(path_args, path_kwargs)
¶
Saves uploaded files, then updates metadata DB
Source code in gramex\handlers\drivehandler.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
|
pre_modify(kwargs)
¶
Called by FormHandler after updating the database, before modify. Save files here.
This allows the DriveHandler modify: action to access the files.
Source code in gramex\handlers\drivehandler.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
|
delete(path_args, path_kwargs)
¶
Deletes files from metadata DB and from file system
Source code in gramex\handlers\drivehandler.py
157 158 159 160 161 162 163 |
|
put(path_args, path_kwargs)
¶
Update attributes and files
Source code in gramex\handlers\drivehandler.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
|
FacebookGraphHandler
¶
Proxy for the Facebook Graph API via these kwargs
:
pattern: /facebook/(.*)
handler: FacebookGraphHandler
kwargs:
key: your-consumer-key
secret: your-consumer-secret
access_token: your-access-token # Optional -- picked up from session
methods: [get, post] # HTTP methods to use for the API
scope: user_posts,user_photos # Permissions requested for the user
path: /me/feed # Freeze Facebook Graph API request
Now POST /facebook/me
returns the same response as the Facebook Graph API
/me
. To request specific access rights, specify the scope
based on
permissions required by the
Graph API.
If you only want to expose a specific API, specify a path:
. It overrides
the URL path. The query parameters will still work.
By default, methods
is POST, and GET logs the user in, storing the access
token in the session for future use. But you can specify the access_token
values and set methods
to [get, post]
to use both GET and POST
requests to proxy the API.
FileHandler
¶
setup(path, default_filename=None, index=None, index_template=None, headers={}, default={}, kwargs)
classmethod
¶
Serves files with transformations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
Can be one of these:
|
required |
default_filename |
str
|
If the URL maps to a directory, this filename
is displayed by default. For example, |
None
|
index |
bool
|
If |
None
|
ignore |
List of glob patterns to ignore. Even if the path matches these, the files will not be served. |
required | |
allow |
List of glob patterns to allow. This overrides the ignore patterns, so use with care. |
required | |
index_template |
str
|
The file to be used as the template for
displaying the index. If this file is missing, it defaults to Gramex’s
default
|
None
|
headers |
dict
|
HTTP headers to set on the response. |
{}
|
transform |
Transformations that should be applied to the files.
The key matches one or more
|
required | |
template |
|
required | |
sass |
|
required | |
scss |
|
required | |
ts |
|
required |
FileHandler exposes these attributes:
root
: Root path for this handler. Aligns with thepath
argumentpath
; Absolute path requested by the user, without adding a default filenamefile
: Absolute path served to the user, after adding a default filename
Source code in gramex\handlers\filehandler.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
|
set(value)
classmethod
¶
Convert value to a set. If value is already a list, set, tuple, return as is. Ensure that the values are non-empty strings.
Source code in gramex\handlers\filehandler.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
|
allowed(path)
¶
A path is allowed if it matches any allow:, or matches no ignore:. Override this method for a custom implementation.
Source code in gramex\handlers\filehandler.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
|
FilterHandler
¶
FormHandler
¶
set_meta_headers(meta)
¶
Add FH-
Source code in gramex\handlers\formhandler.py
280 281 282 283 284 285 286 287 288 |
|
pre_modify(kwargs)
¶
Called after inserting records into DB. Subclasses use it for additional processing
Source code in gramex\handlers\formhandler.py
290 291 292 |
|
FunctionHandler
¶
Renders the output of a function when the URL is called via GET or POST.
function
: A Python expression that can usehandler
as a variable.headers
: HTTP headers to set on the response.redirect
: URL to redirect to when done, e.g. for calculations without output.
The function result is converted to a string and rendered. You can also yield one or more results. These are written immediately, in order.
GoogleAuth
¶
exchange_refresh_token(user, refresh_token=None)
classmethod
¶
Exchange the refresh token for the current user for a new access token.
See https://developers.google.com/android-publisher/authorizatio#using_the_refresh_token
The token is picked up from the persistent user info store. Developers can explicitly pass a refresh_token as well.
Sample usage in a FunctionHandler coroutine
@tornado.gen.coroutine
def refresh(handler):
# Get the Google auth handler though which the current user logged in
auth_handler = gramex.service.url['google-handler'].handler_class
# Exchange refresh token for access token
yield auth_handler.exchange_refresh_token(handler.current_user)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user |
dict
|
current user object, i.e. |
required |
refresh_token |
str
|
optional. By default, the refresh token is picked up from
|
None
|
Source code in gramex\handlers\authhandler.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
|
JSONHandler
¶
setup(path=None, data=None, kwargs)
classmethod
¶
Provides a REST API for managing and persisting JSON data.
Sample URL configuration
pattern: /$YAMLURL/data/(.*)
handler: JSONHandler
kwargs:
path: $YAMLPATH/data.json
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
optional file where the JSON data is persisted. If not specified, the JSON data is not persisted. |
None
|
data |
str
|
optional initial dataset, used only if path is not specified. Defaults to null |
None
|
Source code in gramex\handlers\jsonhandler.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
jsonwalk(jsonpath, create=False)
¶
Return a parent, key, value from the JSON store where parent[key] == value
Source code in gramex\handlers\jsonhandler.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
|
get(jsonpath)
¶
Return the JSON data at jsonpath. Return null for invalid paths.
Source code in gramex\handlers\jsonhandler.py
110 111 112 113 |
|
post(jsonpath)
¶
Add data as a new unique key under jsonpath. Return {name: new_key}
Source code in gramex\handlers\jsonhandler.py
115 116 117 118 119 120 121 122 123 124 125 126 |
|
put(jsonpath)
¶
Set JSON data at jsonpath. Return the data provided
Source code in gramex\handlers\jsonhandler.py
128 129 130 131 132 133 134 135 136 |
|
patch(jsonpath)
¶
Update JSON data at jsonpath. Return the data provided
Source code in gramex\handlers\jsonhandler.py
138 139 140 141 142 143 144 145 |
|
delete(jsonpath)
¶
Delete data at jsonpath. Return null
Source code in gramex\handlers\jsonhandler.py
147 148 149 150 151 152 153 |
|
LogoutHandler
¶
ModelHandler
¶
Allows users to create API endpoints to train/test models exposed through Scikit-Learn. TODO: support Scikit-Learn Pipelines for data transformations.
prepare()
¶
Gets called automatically at the beginning of every request. takes model name from request path and creates the pickle file path. Also merges the request body and the url query args. url query args have precedence over request body in case both exist. Expects multi-row paramets to be formatted as the output of handler.argparse.
Source code in gramex\handlers\modelhandler.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
get_data_flag()
¶
Return a True if the request is made to /model/name/data.
Source code in gramex\handlers\modelhandler.py
41 42 43 44 45 46 |
|
get(path_args)
¶
Request sent to model/name with no args returns model information, (that can be changed via PUT/POST). Request to model/name with args will accept model input and produce predictions. Request to model/name/data will return the training data specified in model.url, this should accept most formhandler flags and filters as well.
Source code in gramex\handlers\modelhandler.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
put(path_args, path_kwargs)
¶
Request to /model/name/ with no params will create a blank model. Request to /model/name/ with args will interpret as model paramters. Set Model-Retrain: true in headers to either train a model from scratch or extend it. To Extend a trained model, don’t update the parameters and send Model-Retrain in headers. Request to /model/name/data with args will update the training data, doesn’t currently work on DF’s thanks to the gramex.data bug.
Source code in gramex\handlers\modelhandler.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
post(path_args, path_kwargs)
¶
Request to /model/name/ with Model-Retrain: true in the headers will, attempt to update model parameters and retrain/extend the model. Request to /model/name/ with model input as body/query args and no Model-Retrain, in headers will return predictions. Request to /model/name/data lets people add rows the test data.
Source code in gramex\handlers\modelhandler.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
delete(path_args)
¶
Request to /model/name/ will delete the trained model. Request to /model/name/data needs id and will delete rows from the training data.
Source code in gramex\handlers\modelhandler.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
|
listify(checklst)
¶
Some functions in data.py expect list values, so creates them. checklst is list-like which contains the selected values to be returned.
Source code in gramex\handlers\modelhandler.py
165 166 167 168 169 170 171 172 173 |
|
MLHandler
¶
MLPredictor
¶
OpenAPIHandler
¶
PPTXHandler
¶
ProcessHandler
¶
setup(args, shell=False, cwd=None, buffer=0, headers={}, kwargs)
classmethod
¶
Set up handler to stream process output.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args |
Union[List[str], str]
|
The first value is the command. The rest are optional string arguments.
Same as |
required |
shell |
bool
|
|
False
|
cwd |
str
|
Current working directory from where the command will run. Defaults to the same directory Gramex ran from. |
None
|
buffer |
Union[str, int]
|
Number of bytes to buffer. Defaults: |
0
|
headers |
dict
|
HTTP headers to set on the response. |
{}
|
Source code in gramex\handlers\processhandler.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
initialize(stdout=None, stderr=None, stdin=None, kwargs)
¶
Sets up I/O stream processing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stdout |
Union[List[str], str]
|
The process output can be sent to |
None
|
stderr |
Union[List[str], str]
|
The process error stream has the same options as stdout. |
None
|
stdin |
Union[List[str], str]
|
(TODO) |
None
|
stdout
, stderr
and stdin
can be one of the below, or a list of the below:
"pipe"
: Display the (transformed) output. This is the default"false"
: Ignore the output"filename.txt"
: Save output to afilename.txt
Source code in gramex\handlers\processhandler.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
|
on_finish()
¶
Close all open handles after the request has finished
Source code in gramex\handlers\processhandler.py
136 137 138 139 140 |
|
ProxyHandler
¶
setup(url, request_headers={}, default={}, prepare=None, modify=None, headers={}, connect_timeout=20, request_timeout=20, kwargs)
classmethod
¶
Passes the request to another HTTP REST API endpoint and returns its response. This is useful when:
- exposing another website but via Gramex authentication (e.g. R-Shiny apps)
- a server-side REST API must be accessed via the browser (e.g. Twitter)
- passing requests to an API that requires authentication (e.g. Google)
- the request or response needs to be transformed (e.g. add sentiment)
- caching is required on the API (e.g. cache for 10 min)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url |
str
|
URL endpoint to forward to. If the pattern ends with
|
required |
request_headers |
dict
|
HTTP headers to be passed to the url.
- |
{}
|
default |
dict
|
Default URL query parameters |
{}
|
headers |
dict
|
HTTP headers to set on the response |
{}
|
prepare |
Callable
|
A function that accepts any of |
None
|
modify |
Callable
|
A function that accepts any of |
None
|
connect_timeout |
int
|
Timeout for initial connection in seconds (default: 20) |
20
|
request_timeout |
int
|
Timeout for entire request in seconds (default: 20) |
20
|
The response has the same HTTP headers and body as the proxied request, but:
- Connection and Transfer-Encoding headers are ignored
X-Proxy-Url:
header has the final URL that responded (after redirects)
These headers can be over-ridden by the headers:
section.
pattern: /gmail/(.*)
handler: ProxyHandler
kwargs:
url: https://www.googleapis.com/gmail/v1/
request_headers:
"*": true # Pass on all HTTP headers
Cookie: true # Pass on the Cookie HTTP header
# Over-ride the Authorization header
Authorization: 'Bearer {handler.session[google_access_token]}'
default:
alt: json
Source code in gramex\handlers\proxyhandler.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
|
SetupFailedHandler
¶
Reports that the setup() operation has failed.
Used by gramex.services.init() when setting up URLs. If it’s not able to set up a handler, it replaces it with this handler.
SimpleAuth
¶
Eventually, change this to use an abstract base class for local authentication methods – i.e. where we render the login screen, not a third party service.
The login page is rendered in case of a login error as well. The page is a
Tornado template that is passed an error
variable. error
is None
by default. If the login fails, it must be a dict
with attributes
specific to the handler.
The simplest configuration (kwargs
) for SimpleAuth is
credentials: # Mapping of user IDs and passwords
user1: password1 # user1 maps to password1
user2: password2
An alternate configuration is
credentials: # Mapping of user IDs and user info
user1: # Each user ID has a dictionary of keys
password: password1 # One of them MUST be password
email: user1@example.org # Any other attributes can be added
role: employee # These are available from the session info
user2:
password: password2
email: user2@example.org
role: manager
The full configuration (kwargs
) for SimpleAuth looks like this
template: $YAMLPATH/auth.template.html # Render the login form template
user:
arg: user # ... the ?user= argument from the form.
password:
arg: password # ... the ?password= argument from the form
data:
... # Same as above
The login flow is as follows:
- User visits the SimpleAuth page => shows template (with the user name and password inputs)
- User enters user name and password, and submits. Browser redirects with a POST request
- Application checks username and password. On match, redirects.
- On any error, shows template (with error)
TwitterRESTHandler
¶
Proxy for the Twitter 1.1 REST API via these kwargs
:
pattern: /twitter/(.*)
handler: TwitterRESTHandler
kwargs:
key: your-consumer-key
secret: your-consumer-secret
access_key: your-access-key # Optional -- picked up from session
access_secret: your-access-token # Optional -- picked up from session
methods: [get, post] # HTTP methods to use for the API
path: /search/tweets.json # Freeze Twitter API request
Now POST /twitter/search/tweets.json?q=gramener
returns the same response
as the Twitter REST API /search/tweets.json
.
If you only want to expose a specific API, specify a path:
. It overrides
the URL path. The query parameters will still work.
By default, methods
is POST, and GET logs the user in, storing the access
token in the session for future use. But you can specify the access_...
values and set methods
to [get, post]
to use both GET and POST
requests to proxy the API.
UploadHandler
¶
UploadHandler lets users upload files. Here’s a typical configuration:
path: /$GRAMEXDATA/apps/appname/ # Save files here
keys: [upload, file] # <input name=""> can be upload / file
store:
type: sqlite # Store metadata in a SQLite store
path: ... # ... at the specified path
redirect: # After uploading the file,
query: next # ... redirect to ?next=
url: /$YAMLURL/ # ... else to this directory
WebSocketHandler
¶
Creates a websocket microservice.
open
: function.open(handler)
is called when the connection is openedon_message
: function.on_message(handler, message: str)
is called when client sends a messageon_close
: function.on_close(handler)
is called when connection is closed.origins
: a domain name or list of domain names. No wildcards
Functions can use handler.write_message(msg: str)
to sends a message back to the client.