If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model):
()
| 194 | |
| 195 | |
| 196 | def has_request_context() -> bool: |
| 197 | """If you have code that wants to test if a request context is there or |
| 198 | not this function can be used. For instance, you may want to take advantage |
| 199 | of request information if the request object is available, but fail |
| 200 | silently if it is unavailable. |
| 201 | |
| 202 | :: |
| 203 | |
| 204 | class User(db.Model): |
| 205 | |
| 206 | def __init__(self, username, remote_addr=None): |
| 207 | self.username = username |
| 208 | if remote_addr is None and has_request_context(): |
| 209 | remote_addr = request.remote_addr |
| 210 | self.remote_addr = remote_addr |
| 211 | |
| 212 | Alternatively you can also just test any of the context bound objects |
| 213 | (such as :class:`request` or :class:`g`) for truthness:: |
| 214 | |
| 215 | class User(db.Model): |
| 216 | |
| 217 | def __init__(self, username, remote_addr=None): |
| 218 | self.username = username |
| 219 | if remote_addr is None and request: |
| 220 | remote_addr = request.remote_addr |
| 221 | self.remote_addr = remote_addr |
| 222 | |
| 223 | .. versionadded:: 0.7 |
| 224 | """ |
| 225 | return _cv_request.get(None) is not None |
| 226 | |
| 227 | |
| 228 | def has_app_context() -> bool: |