gramex.transforms
¶
Utility functions for actions or conversions
ensure_single_session(handler)
¶
Log user out of all sessions except this handler’s.
This is used in any auth handler, e.g. SimpleAuth or GoogleAuth, as a login action:
pattern: /login/
handler: GoogleAuth # or any auth
kwargs:
action:
- function: ensure_single_session
It removes the user object from all sessions except the session of this handler.
Source code in gramex\transforms\auth.py
5 6 7 8 9 10 11 12 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 |
|
scss(content, handler)
¶
Renders a SCSS file as CSS in a FileHandler.
This can be used as a keyword argument to FileHandler:
pattern: /file.scss
handler: FileHandler
kwargs:
...
scss: '*.scss'
Source code in gramex\transforms\template.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
|
ts(content, handler)
¶
Render a TypeScript file as JavaScript in a FileHandler.
This can be used as a keyword argument to FileHandler:
pattern: /file.ts
handler: FileHandler
kwargs:
...
ts: '*.ts'
Source code in gramex\transforms\template.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
build_transform(conf, vars=None, kwargs=False, filename='transform', cache=False, iter=True)
¶
Converts an expression into a callable function.
Examples:
>>> fn = build_transform({'function': 'json.dumps({"x": 1})'}, iter=False)
>>> fn()
... '{"x": 1}'
This compiles the expression into a callable function as follows:
def transform(_val):
import json
result = json.dumps({"x": 1})
return result
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conf |
dict
|
expression to compile |
required |
vars |
dict
|
variables passed to the compiled function |
None
|
kwargs |
Union[bool, str]
|
|
False
|
filename |
str
|
filename to print in case of errors |
'transform'
|
cache |
bool
|
|
False
|
iter |
bool
|
|
True
|
conf
is a dict with a function
key with Python expression. This expression is compiled
and returned. If the expression uses modules (e.g. json.dumps
), they are auto-imported.
It optionally accepts an args
list and a kwargs
list if function
is a function name.
Examples:
>>> {'function': '1'} # => 1
>>> {'function': 'x + y'} # => x + y
>>> {'function': 'json.dumps(x)'} # => json.dumps(s)
>>> {'function': 'json.dumps', 'args': ['x'], 'kwargs': {'indent': 2}}
>>> {'function': 'json.dumps("x", indent=2)` # same as above
args
values and kwargs
keys are treated as strings, not variables. But values starting with
=
(e.g. =handler
) are treated as variables. (Use ==x
to represent the string =x
.)
Examples:
>>> {'function': 'str', 'args': ['handler']} # => str('handler')
>>> {'function': 'str', 'args': ['=handler']} # => str(handler)
>>> {'function': 'str', 'args': ['==handler']} # => str('=handler')
vars
defines the compiled function’s signature. vars={'x': 1, 'y': 2}
creates a
def transform(x=1, y=2):
.
vars
defaults to {'_val': None}
.
Examples:
>>> add = build_transform({'function': 'x + y'}, vars={'x': 1, 'y': 2}, iter=False)
>>> add()
... 3
>>> add(x=3)
... 5
>>> add(x=3, y=4)
... 7
>>> incr = build_transform({'function': '_val + 1'}, iter=False)
>>> incr(3)
... 4
kwargs=True
allows the compiled function to accept any keyword arguments as **kwargs
.
Specify kwargs='kw'
to use kw
(or any string) as the keyword arguments variable instead.
Examples:
>>> params = build_transform({'function': 'kwargs'}, vars={}, kwargs=True, iter=False)
>>> params(x=1)
... {'x': 1}
>>> params(x=1, y=2)
... {'x': 1, 'y': 2}
>>> params = build_transform({'function': 'kw'}, vars={}, kwargs='kw', iter=False)
>>> params(x=1, y=2)
... {'x': 1, 'y': 2}
filename
defines the filename printed in error messages.
Examples:
>>> error = build_transform({'function': '1/0'}, filename='zero-error', iter=False)
... Traceback (most recent call last):
... File "<stdin>", line 1, in <module>
... File "zero-error", line 2, in transform
... ZeroDivisionError: division by zero
cache=False
re-imports the modules if changed. This is fairly efficient, and is the default.
Use cache=True
to cache modules until Python is restarted.
iter=True
always returns an iterable. If the function
is a generator (i.e. has a yield
),
it is returned as-is. Else it is returned as an array, i.e. [result]
.
Examples:
build_transform()
returns results wrapped as an array.
>>> val = build_transform({'function': '4'})
>>> val()
... [4]
>>> val = build_transform({'function': '[4, 5]'})
>>> val()
... [[4, 5]]
If the result is a generator, it is returned as-is.
>>> def gen():
... for x in range(5):
... yield x
>>> val = build_transform({'function': 'fn()'}, vars={'fn': None})
>>> val(gen)
... <generator object gen at 0x....>
>>> list(val(gen))
... [0, 1, 2, 3, 4]
If iter=False
, it returns the results as-is.
>>> val = build_transform({'function': '4'}, iter=False)
>>> val()
... 4
>>> val = build_transform({'function': '[4, 5]'}, iter=False)
>>> val()
... [4, 5]
Source code in gramex\transforms\transforms.py
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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 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 |
|
build_pipeline(conf, vars=None, kwargs=False, filename='pipeline', cache=False, iter=True)
¶
Converts an expression list into a callable function (called a pipeline).
Examples:
>>> fn = build_pipeline([
... {'name': 'x', 'function': '1 + 2'},
... {'name': 'y', 'function': '3 + 4'},
... {'function': 'x + y'},
... ], iter=False)
>>> fn()
... 10
This compiles the expression list into a callable function roughty as follows:
def pipeline(_val):
x = 1 + 2
y = 3 + 4
return x + y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conf |
dict
|
expression list to compile |
required |
vars |
dict
|
variables passed to the compiled function |
None
|
kwargs |
Union[bool, str]
|
|
False
|
filename |
str
|
filename to print in case of errors |
'pipeline'
|
cache |
bool
|
|
False
|
iter |
bool
|
|
True
|
conf
is a list of the same conf
that
build_transform accepts.
Other parameters are the same as build_transform.
Source code in gramex\transforms\transforms.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
|
condition(args)
¶
Deprecated
Use the if
construct in config keys instead.
Variables can also be computed based on conditions
variables: OS: default: ‘No OS variable defined’ PORT: function: condition args: - $OS.startswith(‘Windows’) - 9991 - $OS.startswith(‘Linux’) - 9992 - 8883
Source code in gramex\transforms\transforms.py
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
|
flattener(fields, default=None, filename='flatten')
¶
Generates a function that flattens deep dictionaries.
Examples:
>>> flat = flattener({
... 'id': 'id',
... 'name': 'user.screen_name'
... })
>>> flat({'id': 1, 'user': {'screen_name': 'name'}})
... {'id': 1, 'name': 'name'}
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fields |
dict
|
a mapping of keys to object paths |
required |
default |
Any
|
the value to use if the object path is not found |
None
|
filename |
str
|
filename to print in case of errors |
'flatten'
|
Object paths are dot-seperated, and constructed as follows:
'1' => obj[1]
'x' => obj['x']
'x.y' => obj['x']['y']
'1.x' => obj[1]['x']
Source code in gramex\transforms\transforms.py
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 564 565 566 567 568 569 570 |
|
once(args, kwargs)
¶
Returns False
if once() has been called before with these arguments. Else True
.
Data is stored in a persistent SQLite dict.
Source code in gramex\transforms\transforms.py
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 |
|
handler(func)
¶
Wrap a function to make it compatible with a FunctionHandler.
Use this decorator to expose a function as a REST API, with path or URL parameters mapped to function arguments with type conversion.
Suppose you have the following function in greet.py
:
@handler
def birthday(name: str, age: int):
return f'{name} turns {age:d} today! Happy Birthday!'
Then, in gramex.yaml
, you can use it as a FunctionHandler as follows::
url:
pattern: /$YAMLURL/greet
handler: FunctionHandler
kwargs:
function: greet.birthday
Now, /greet?name=Gramex&age=0010
returns “Gramex turns 10 today! Happy Birthday!”.
It converts the URL parameters into the types found in the annotations, e.g. 0010
into 10.
An alternate way of configuring this is as follows::
url:
pattern: /$YAMLURL/greet/name/(.*)/age/(.*)
handler: FunctionHandler
kwargs:
# You can pass name=... and age=... as default values
# but ensure that handler is the first argument in the config.
function: greet.birthday(handler, name='Name', age=10)
Now, /greet/name/Gramex/age/0010
returns “Gramex turns 10 today! Happy Birthday!”.
The function args and kwargs are taken from these sources this in order.
- From the YAML function
- e.g.
function: greet.birthday('Name', age=10)
setsname='Name'
andage=10
- e.g.
- Over-ridden by YAML URL pattern
- e.g.
pattern: /$YAMLPATH/(.*)/(?P<age>.*)
- URL
/greet/Name/10
setsname='Name'
andage=10
- e.g.
- Over-ridden by URL query parameters
- e.g. URL
/greet?name=Name&age=10
setsname='Name'
andage=10
- e.g. URL
- Over-ridden by URL POST body parameters
- e.g.
curl -X POST /greet -d "?name=Name&age=10"
setsname='Name'
andage=10
- e.g.
handler
is also available as a kwarg. You can use this as the last positional argument or
a keyword argument. Both def birthday(name, age, handler)
and
def birthday(name, age, handler=None)
are valid.
Source code in gramex\transforms\transforms.py
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 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 |
|
build_log_info(keys, vars)
¶
Utility to create logging values.
Returns a function that accepts a handler and returns a dict of values to log.
Examples:
>>> log_info = build_log_info(['time', 'ip', 'cookies.sid', 'user.email'])
>>> log_info(handler)
... {"time": 1655280440, "ip": "::1", "cookies.sid": "...", "user.email": "..."}
Parameters:
Name | Type | Description | Default |
---|---|---|---|
keys |
List
|
list of keys to include in the log. |
required |
*vars |
List
|
additional variables to include in the log. |
()
|
keys
can include: name
, class
, time
, datetime
, method
, uri
, ip
, status
,
duration
, port, user
, session
, error
.
It can also include:
args.*
: value of the URL query parameter ?arg=request.*
: value ofhandler.request.*
headers.*
: value of the HTTP headercookies.*
: value of the HTTP cookieuser.*
: key in the user objectenv.*
: value of the environment variable
vars
can be any list of any variables. When you pass these to the function, they’re added to
the returned value as-is. (This is used internally in [gramex.handlers.AuthHandler.setup])
Examples:
>>> log_info = build_log_info(['time'], 'event')
>>> log_info(handler, event='x')
... {"time": 1655280440, "event": "x"}
Source code in gramex\transforms\transforms.py
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 |
|