| | 1 | {{{ |
| | 2 | #!rst |
| | 3 | |
| | 4 | .. |
| | 5 | ============================ |
| | 6 | Request and response objects |
| | 7 | ============================ |
| | 8 | |
| | 9 | =============================== |
| | 10 | Oggetti di richiesta e risposta |
| | 11 | =============================== |
| | 12 | |
| | 13 | .. sidebar:: Oggetti di richiesta e risposta |
| | 14 | :subtitle: traduzione in lingua italiana. |
| | 15 | |
| | 16 | Documento originale: `Request and response objects`_ |
| | 17 | |
| | 18 | Traduzione: paolo `<paolo@php3.it>` |
| | 19 | |
| | 20 | Aggiornato alla revisione: 2869 |
| | 21 | |
| | 22 | .. _Request and response objects: http://www.djangoproject.com/documentation/request_response/ |
| | 23 | |
| | 24 | .. |
| | 25 | Quick overview |
| | 26 | ============== |
| | 27 | |
| | 28 | Breve panoramica |
| | 29 | ================ |
| | 30 | |
| | 31 | .. |
| | 32 | Django uses request and response objects to pass state through the system. |
| | 33 | |
| | 34 | Django usa oggetti di richiesta e risposta per passare lo stato nel sistema. |
| | 35 | |
| | 36 | .. |
| | 37 | When a page is requested, Django creates an ``HttpRequest`` object that |
| | 38 | contains metadata about the request. Then Django loads the appropriate view, |
| | 39 | passing the ``HttpRequest`` as the first argument to the view function. Each |
| | 40 | view is responsible for returning an ``HttpResponse`` object. |
| | 41 | |
| | 42 | Quando è richiesta una pagina, Django crea un oggetto ``HttpRequest`` contenente |
| | 43 | i metadati relativi alla richiesta effettuata. Poi avviene il caricamento |
| | 44 | della view appropriata ed il passaggio dell'oggetto ``HttpRequest`` alla funzione |
| | 45 | corrispondente alla view, come primo argomento. Infine, ogni view |
| | 46 | è tenuta a fornire come risposta un oggetto ``HttpResponse``. |
| | 47 | |
| | 48 | .. |
| | 49 | This document explains the APIs for ``HttpRequest`` and ``HttpResponse`` |
| | 50 | objects. |
| | 51 | |
| | 52 | Questo documento descrive le API relative agli oggetti ``HttpRequest`` e |
| | 53 | ``HttpResponse``. |
| | 54 | |
| | 55 | .. |
| | 56 | HttpRequest objects |
| | 57 | =================== |
| | 58 | |
| | 59 | Oggetti HttpRequest |
| | 60 | =================== |
| | 61 | |
| | 62 | .. |
| | 63 | Attributes |
| | 64 | ---------- |
| | 65 | |
| | 66 | Attributi |
| | 67 | --------- |
| | 68 | |
| | 69 | .. All attributes except ``session`` should be considered read-only. |
| | 70 | |
| | 71 | Tutti gli attributi eccetto ``session`` sono utilizzabili in sola lettura. |
| | 72 | |
| | 73 | .. |
| | 74 | ``path`` |
| | 75 | A string representing the full path to the requested page, not including |
| | 76 | the domain. |
| | 77 | |
| | 78 | Example: ``"/music/bands/the_beatles/"`` |
| | 79 | |
| | 80 | ``path`` |
| | 81 | Una stringa che rappresenta il percorso completo della pagina richiesta, |
| | 82 | escludendo il nome del dominio. |
| | 83 | |
| | 84 | Esempio: ``"/music/bands/the_beatles/"`` |
| | 85 | |
| | 86 | .. |
| | 87 | ``GET`` |
| | 88 | A dictionary-like object containing all given HTTP GET parameters. See the |
| | 89 | ``QueryDict`` documentation below. |
| | 90 | |
| | 91 | ``GET`` |
| | 92 | Un oggetto "dictionary-like" contenente tutti i parametri HTTP GET |
| | 93 | che sono stati specificati. Vedi la documentazione seguente relativa a |
| | 94 | ``QueryDict``. |
| | 95 | |
| | 96 | .. |
| | 97 | ``POST`` |
| | 98 | A dictionary-like object containing all given HTTP POST parameters. See the |
| | 99 | ``QueryDict`` documentation below. |
| | 100 | |
| | 101 | Note: ``POST`` does *not* include file-upload information. See ``FILES``. |
| | 102 | |
| | 103 | ``POST`` |
| | 104 | Un oggetto "dictionary-like" contenente tutti i parametri HTTP POST |
| | 105 | che sono stati specificati. Vedi la documentazione seguente relativa a |
| | 106 | ``QueryDict``. |
| | 107 | |
| | 108 | Nota: l'attributo ``POST`` *non* include le informazioni sui file caricati |
| | 109 | tramite form. |
| | 110 | Per questo vedi la sezione ``FILES``. |
| | 111 | |
| | 112 | .. |
| | 113 | ``REQUEST`` |
| | 114 | For convenience, a dictionary-like object that searches ``POST`` first, |
| | 115 | then ``GET``. Inspired by PHP's ``$_REQUEST``. |
| | 116 | |
| | 117 | For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``, |
| | 118 | ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be |
| | 119 | ``"34"``. |
| | 120 | |
| | 121 | It's strongly suggested that you use ``GET`` and ``POST`` instead of |
| | 122 | ``REQUEST``, because the former are more explicit. |
| | 123 | |
| | 124 | ``REQUEST`` |
| | 125 | Definito per comodità, è un oggetto "dictionary-like" in cui la |
| | 126 | ricerca dei parametri avviene prima usando l'attributo ``POST``, poi |
| | 127 | usando ``GET``. L'idea di implementare ``REQUEST`` è nata prendendo spunto |
| | 128 | da ``$_REQUEST`` di PHP. |
| | 129 | |
| | 130 | Ad esempio, se ``GET = {"name": "john"}`` e ``POST = {"age": '34'}``, |
| | 131 | ``REQUEST["name"]`` restituirebbe ``"john"``, e ``REQUEST["age"]`` restituirebbe |
| | 132 | ``"34"``. |
| | 133 | |
| | 134 | E' vivamente consigliato l'utilizzo di ``GET`` e ``POST`` al posto di |
| | 135 | ``REQUEST``, in quanto le prime due formule risultano più esplicite. |
| | 136 | |
| | 137 | .. |
| | 138 | ``COOKIES`` |
| | 139 | A standard Python dictionary containing all cookies. Keys and values are |
| | 140 | strings. |
| | 141 | |
| | 142 | ``COOKIES`` |
| | 143 | E' un dizionario contenente tutti i cookies. Le chiavi e valori sono |
| | 144 | stringhe. |
| | 145 | |
| | 146 | .. |
| | 147 | ``FILES`` |
| | 148 | A dictionary-like object containing all uploaded files. Each key in |
| | 149 | ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each |
| | 150 | value in ``FILES`` is a standard Python dictionary with the following three |
| | 151 | keys: |
| | 152 | |
| | 153 | * ``filename`` -- The name of the uploaded file, as a Python string. |
| | 154 | * ``content-type`` -- The content type of the uploaded file. |
| | 155 | * ``content`` -- The raw content of the uploaded file. |
| | 156 | |
| | 157 | Note that ``FILES`` will only contain data if the request method was POST |
| | 158 | and the ``<form>`` that posted to the request had |
| | 159 | ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank |
| | 160 | dictionary-like object. |
| | 161 | |
| | 162 | ``FILES`` |
| | 163 | Un oggetto "dictionary-like" contenente le informazioni su tutti i |
| | 164 | file caricati dall'utente tramite form. Ogni chiave di ``FILES`` |
| | 165 | coincide con il valore di ``name`` ottenuto da ``<input type="file" name="" />``. |
| | 166 | Ogni valore invece è un normale dizionario in cui compaiono tre chiavi: |
| | 167 | |
| | 168 | * ``filename`` -- Il nome del file, come stringa. |
| | 169 | * ``content-type`` -- Il tipo di contenuto del file. |
| | 170 | * ``content`` -- Il contenuto del file. |
| | 171 | |
| | 172 | Nota che l'attributo ``FILES`` conterrà dati solamente se il metodo della |
| | 173 | richiesta è di tipo POST e il tipo di contenuto specificato in ``<form>`` |
| | 174 | mediante enctype risulta essere ``multipart/form-data`` |
| | 175 | (``enctype="multipart/form-data"``). Diversamente ``FILES`` sarà un oggetto |
| | 176 | "dictionary-like" vuoto. |
| | 177 | |
| | 178 | .. |
| | 179 | ``META`` |
| | 180 | A standard Python dictionary containing all available HTTP headers. |
| | 181 | Available headers depend on the client and server, but here are some |
| | 182 | examples: |
| | 183 | |
| | 184 | * ``CONTENT_LENGTH`` |
| | 185 | * ``CONTENT_TYPE`` |
| | 186 | * ``HTTP_ACCEPT_ENCODING`` |
| | 187 | * ``HTTP_ACCEPT_LANGUAGE`` |
| | 188 | * ``HTTP_REFERER`` -- The referring page, if any. |
| | 189 | * ``HTTP_USER_AGENT`` -- The client's user-agent string. |
| | 190 | * ``QUERY_STRING`` -- The query string, as a single (unparsed) string. |
| | 191 | * ``REMOTE_ADDR`` -- The IP address of the client. |
| | 192 | * ``REMOTE_HOST`` -- The hostname of the client. |
| | 193 | * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``. |
| | 194 | * ``SERVER_NAME`` -- The hostname of the server. |
| | 195 | * ``SERVER_PORT`` -- The port of the server. |
| | 196 | |
| | 197 | ``META`` |
| | 198 | E' un dizionario contenente tutti gli header HTTP disponibili. In |
| | 199 | genere la disponibilità degli header varia in funzione del client e del |
| | 200 | server; di seguito sono elencate alcune intestazioni HTTP a titolo di |
| | 201 | esempio: |
| | 202 | |
| | 203 | * ``CONTENT_LENGTH`` |
| | 204 | * ``CONTENT_TYPE`` |
| | 205 | * ``HTTP_ACCEPT_ENCODING`` |
| | 206 | * ``HTTP_ACCEPT_LANGUAGE`` |
| | 207 | * ``HTTP_REFERER`` -- La pagina di provenienza, se esiste. |
| | 208 | * ``HTTP_USER_AGENT`` -- La stringa di identificazione del browser che ha effettuato la richiesta. |
| | 209 | * ``QUERY_STRING`` -- La stringa contenente i parametri, sottoforma di un'unica stringa non elaborata. |
| | 210 | * ``REMOTE_ADDR`` -- L'indirizzo IP del client. |
| | 211 | * ``REMOTE_HOST`` -- Il nome host del client. |
| | 212 | * ``REQUEST_METHOD`` -- Una stringa come ``"GET"`` o ``"POST"``. |
| | 213 | * ``SERVER_NAME`` -- Il nome host del server. |
| | 214 | * ``SERVER_PORT`` -- La porta di comunicazione del server. |
| | 215 | |
| | 216 | |
| | 217 | .. |
| | 218 | ``user`` |
| | 219 | A ``django.contrib.auth.models.User`` object representing the currently |
| | 220 | logged-in user. If the user isn't currently logged in, ``user`` will be set |
| | 221 | to an instance of ``django.contrib.auth.models.AnonymousUser``. You |
| | 222 | can tell them apart with ``is_anonymous()``, like so:: |
| | 223 | |
| | 224 | if request.user.is_anonymous(): |
| | 225 | # Do something for anonymous users. |
| | 226 | else: |
| | 227 | # Do something for logged-in users. |
| | 228 | |
| | 229 | ``user`` is only available if your Django installation has the |
| | 230 | ``AuthenticationMiddleware`` activated. For more, see |
| | 231 | `Authentication in Web requests`_. |
| | 232 | |
| | 233 | .. _Authentication in Web requests: http://www.djangoproject.com/documentation/authentication/#authentication-in-web-requests |
| | 234 | |
| | 235 | ``user`` |
| | 236 | Rappresenta l'utente attualmente loggato come oggetto |
| | 237 | ``django.contrib.auth.models.User``. Se non sono disponibili le credenziali |
| | 238 | d'accesso dell'utente che ha effettuato la richiesta, ``user`` conterrà |
| | 239 | un'istanza di ``django.contrib.auth.models.AnonymousUser``. Puoi |
| | 240 | diversificare le possibilità per questo tipo di utente rispetto agli |
| | 241 | utenti loggati usando ``is_anonymous()`` come nell'esempio:: |
| | 242 | |
| | 243 | if request.user.is_anonymous(): |
| | 244 | # Fai qualcosa per gli utenti anonimi. |
| | 245 | else: |
| | 246 | # Fai qualcosa per gli utenti autenticati. |
| | 247 | |
| | 248 | ``user`` è disponibile soltanto se ``AuthenticationMiddleware`` è stato |
| | 249 | attivato per questa installazione di Django. Per ulteriori dettagli consulta |
| | 250 | `Autenticazione nelle richieste Web`_. |
| | 251 | |
| | 252 | .. _Autenticazione nelle richieste Web: http://www.djangoproject.com/documentation/authentication/#authentication-in-web-requests |
| | 253 | |
| | 254 | .. |
| | 255 | ``session`` |
| | 256 | A readable-and-writable, dictionary-like object that represents the current |
| | 257 | session. This is only available if your Django installation has session |
| | 258 | support activated. See the `session documentation`_ for full details. |
| | 259 | |
| | 260 | .. _`session documentation`: http://www.djangoproject.com/documentation/sessions/ |
| | 261 | |
| | 262 | ``session`` |
| | 263 | E' un oggetto "dictionary-like" a cui si può accedere in lettura e |
| | 264 | scrittura con cui viene rappresentata la sessione corrente. L'oggetto |
| | 265 | session è disponibile solamente se nell'installazione di Django è attivo il |
| | 266 | supporto per le sessioni. Per i dettagli completi consulta la |
| | 267 | `documentazione relativa alle sessioni`_. |
| | 268 | |
| | 269 | .. _`documentazione relativa alle sessioni`: http://www.djangoproject.com/documentation/sessions/ |
| | 270 | |
| | 271 | .. |
| | 272 | ``raw_post_data`` |
| | 273 | The raw HTTP POST data. This is only useful for advanced processing. Use |
| | 274 | ``POST`` instead. |
| | 275 | |
| | 276 | ``raw_post_data`` |
| | 277 | I dati grezzi di HTTP POST. Viene usato per elaborazioni avanzate. |
| | 278 | Nella maggior parte dei casi userai ``POST`` invece di ``raw_post_data``. |
| | 279 | |
| | 280 | .. |
| | 281 | Methods |
| | 282 | ------- |
| | 283 | |
| | 284 | Metodi |
| | 285 | ------ |
| | 286 | |
| | 287 | .. |
| | 288 | ``__getitem__(key)`` |
| | 289 | Returns the GET/POST value for the given key, checking POST first, then |
| | 290 | GET. Raises ``KeyError`` if the key doesn't exist. |
| | 291 | |
| | 292 | This lets you use dictionary-accessing syntax on an ``HttpRequest`` |
| | 293 | instance. Example: ``request["foo"]`` would return ``True`` if either |
| | 294 | ``request.POST`` or ``request.GET`` had a ``"foo"`` key. |
| | 295 | |
| | 296 | ``__getitem__(key)`` |
| | 297 | Restituisce il valore GET/POST per la chiave specificata (key), controllando |
| | 298 | prima POST poi GET. Solleva un'eccezione ``KeyError`` se la chiave non |
| | 299 | esiste. |
| | 300 | |
| | 301 | Questo consente di accedere ad una istanza ``HttpRequest`` usando la |
| | 302 | sintassi con cui normalmente si accede ai dizionari. Ad esempio: |
| | 303 | ``request["foo"]`` restituisce ``True`` se ``"foo"`` è presente come chiave in |
| | 304 | ``request.POST`` o ``request.GET`` |
| | 305 | |
| | 306 | .. |
| | 307 | ``has_key()`` |
| | 308 | Returns ``True`` or ``False``, designating whether ``request.GET`` or |
| | 309 | ``request.POST`` has the given key. |
| | 310 | |
| | 311 | ``has_key()`` |
| | 312 | Restituisce ``True`` o ``False``, indicando se la chiave specificata è |
| | 313 | presente in ``request.GET`` o in ``request.POST``. |
| | 314 | |
| | 315 | .. |
| | 316 | ``get_full_path()`` |
| | 317 | Returns the ``path``, plus an appended query string, if applicable. |
| | 318 | |
| | 319 | Example: ``"/music/bands/the_beatles/?print=true"`` |
| | 320 | |
| | 321 | ``get_full_path()`` |
| | 322 | Restituisce il ``path``, accodando la query string, se presente. |
| | 323 | |
| | 324 | Ad esempio: ``"/music/bands/the_beatles/?print=true"`` |
| | 325 | |
| | 326 | .. |
| | 327 | QueryDict objects |
| | 328 | ----------------- |
| | 329 | |
| | 330 | Oggetti QueryDict |
| | 331 | ----------------- |
| | 332 | |
| | 333 | .. |
| | 334 | In an ``HttpRequest`` object, the ``GET`` and ``POST`` attributes are instances |
| | 335 | of ``django.http.QueryDict``. ``QueryDict`` is a dictionary-like |
| | 336 | class customized to deal with multiple values for the same key. This is |
| | 337 | necessary because some HTML form elements, notably |
| | 338 | ``<select multiple="multiple">``, pass multiple values for the same key. |
| | 339 | |
| | 340 | Gli attributi ``GET`` e ``POST`` di un oggetto ``HttpRequest`` sono istanze di |
| | 341 | ``django.http.QueryDict``. ``QueryDict`` è una classe "dictionary-like", cioè |
| | 342 | simile ad un dizionario, progettata per gestire molteplici valori per una |
| | 343 | stessa chiave. Ciò si rende necessario perché alcuni elementi relativi ai form |
| | 344 | HTML, in particolare ``<select multiple="multiple">``, passano più valori per |
| | 345 | la stessa chiave. |
| | 346 | |
| | 347 | .. |
| | 348 | ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them. |
| | 349 | That means you can't change attributes of ``request.POST`` and ``request.GET`` |
| | 350 | directly. |
| | 351 | |
| | 352 | Le istanze ``QueryDict`` sono immutabili, a meno che ne venga creata una copia |
| | 353 | con ``copy()``. Ne segue che non puoi cambiare direttamente gli attributi di |
| | 354 | ``request.POST`` e ``request.GET``. |
| | 355 | |
| | 356 | .. |
| | 357 | ``QueryDict`` implements the all standard dictionary methods, because it's a |
| | 358 | subclass of dictionary. Exceptions are outlined here: |
| | 359 | |
| | 360 | Essendo ``QueryDict`` una classe derivata dagli oggetti dizionario, tutti i |
| | 361 | metodi standard propri dei dizionari vengono implementati, con le differenze |
| | 362 | elencate di seguito: |
| | 363 | |
| | 364 | .. |
| | 365 | * ``__getitem__(key)`` -- Returns the value for the given key. If the key |
| | 366 | has more than one value, ``__getitem__()`` returns the last value. |
| | 367 | |
| | 368 | * ``__getitem__(key)`` -- Restituisce il valore corrispondente alla |
| | 369 | chiave fornita (key), o l'ultimo dei valori se la chiave è associata a più di |
| | 370 | un valore. |
| | 371 | |
| | 372 | .. |
| | 373 | * ``__setitem__(key, value)`` -- Sets the given key to ``[value]`` |
| | 374 | (a Python list whose single element is ``value``). Note that this, as |
| | 375 | other dictionary functions that have side effects, can only be called on |
| | 376 | a mutable ``QueryDict`` (one that was created via ``copy()``). |
| | 377 | |
| | 378 | * ``__setitem__(key, value)`` -- Imposta la chiave specificata (key) al |
| | 379 | valore ``[value]`` (una lista Python il cui singolo elemento è ``value``). |
| | 380 | Nota che questa funzione, come le altre funzioni sui dizionari che prevedano |
| | 381 | conseguenze "attive", può essere eseguita soltanto su ``QueryDict`` mutabili |
| | 382 | (quelli creati usando ``copy()``). |
| | 383 | |
| | 384 | .. |
| | 385 | * ``__contains__(key)`` -- Returns ``True`` if the given key is set. This |
| | 386 | lets you do, e.g., ``if "foo" in request.GET``. |
| | 387 | |
| | 388 | * ``__contains__(key)`` -- Restituisce ``True`` se la chiave (key) è |
| | 389 | impostata. In questo modo è possibile, ad esempio, scrivere: |
| | 390 | ``if "foo" in request.GET``. |
| | 391 | |
| | 392 | .. |
| | 393 | * ``get(key, default)`` -- Uses the same logic as ``__getitem__()`` above, |
| | 394 | with a hook for returning a default value if the key doesn't exist. |
| | 395 | |
| | 396 | * ``get(key, default)`` -- Usa la stessa logica adottata da |
| | 397 | ``__getitem__()`` restituendo un valore predefinito (default) se la |
| | 398 | chiave (key) non esiste. |
| | 399 | |
| | 400 | .. |
| | 401 | * ``has_key(key)`` |
| | 402 | |
| | 403 | * ``has_key(key)`` |
| | 404 | |
| | 405 | .. |
| | 406 | * ``setdefault(key, default)`` -- Just like the standard dictionary |
| | 407 | ``setdefault()`` method, except it uses ``__setitem__`` internally. |
| | 408 | |
| | 409 | * ``setdefault(key, default)`` -- equivalente al metodo |
| | 410 | ``setdefault()`` dei dizionari usuali, eccetto per l'utilizzo |
| | 411 | interno di ``__setitem__``. |
| | 412 | |
| | 413 | .. |
| | 414 | * ``update(other_dict)`` -- Takes either a ``QueryDict`` or standard |
| | 415 | dictionary. Just like the standard dictionary ``update()`` method, except |
| | 416 | it *appends* to the current dictionary items rather than replacing them. |
| | 417 | For example:: |
| | 418 | |
| | 419 | >>> q = QueryDict('a=1') |
| | 420 | >>> q = q.copy() # to make it mutable |
| | 421 | >>> q.update({'a': '2'}) |
| | 422 | >>> q.getlist('a') |
| | 423 | ['1', '2'] |
| | 424 | >>> q['a'] # returns the last |
| | 425 | ['2'] |
| | 426 | |
| | 427 | * ``update(other_dict)`` -- Accetta un ``QueryDict`` o un normale |
| | 428 | dizionario. Si comporta come il metodo ``update()`` dei normali |
| | 429 | dizionari, salvo per il fatto di accodare gli elementi al dizionario |
| | 430 | corrente, invece di rimpiazzarli. |
| | 431 | Ad esempio:: |
| | 432 | |
| | 433 | >>> q = QueryDict('a=1') |
| | 434 | >>> q = q.copy() # lo rende mutabile |
| | 435 | >>> q.update({'a': '2'}) |
| | 436 | >>> q.getlist('a') |
| | 437 | ['1', '2'] |
| | 438 | >>> q['a'] # restituisce l'ultimo |
| | 439 | ['2'] |
| | 440 | |
| | 441 | .. |
| | 442 | * ``items()`` -- Just like the standard dictionary ``items()`` method, |
| | 443 | except this uses the same last-value logic as ``__getitem()__``. For |
| | 444 | example:: |
| | 445 | |
| | 446 | >>> q = QueryDict('a=1&a=2&a=3') |
| | 447 | >>> q.items() |
| | 448 | [('a', '3')] |
| | 449 | |
| | 450 | * ``items()`` -- Si comporta come il metodo ``items()`` dei normali |
| | 451 | dizionari, salvo per il fatto che viene usata la logica adottata da |
| | 452 | ``__getitem()__`` di restituire l'ultimo valore. Ad esempio:: |
| | 453 | |
| | 454 | >>> q = QueryDict('a=1&a=2&a=3') |
| | 455 | >>> q.items() |
| | 456 | [('a', '3')] |
| | 457 | |
| | 458 | .. |
| | 459 | * ``values()`` -- Just like the standard dictionary ``values()`` method, |
| | 460 | except this uses the same last-value logic as ``__getitem()__``. For |
| | 461 | example:: |
| | 462 | |
| | 463 | >>> q = QueryDict('a=1&a=2&a=3') |
| | 464 | >>> q.values() |
| | 465 | ['3'] |
| | 466 | |
| | 467 | * ``values()`` -- Si comporta come il metodo ``values()`` dei normali |
| | 468 | dizionari, salvo per il fatto che viene usata la logica di restituire |
| | 469 | l'ultimo valore adottata da ``__getitem()__``. Ad esempio:: |
| | 470 | |
| | 471 | >>> q = QueryDict('a=1&a=2&a=3') |
| | 472 | >>> q.values() |
| | 473 | ['3'] |
| | 474 | |
| | 475 | .. In addition, ``QueryDict`` has the following methods: |
| | 476 | |
| | 477 | In aggiunta, ``QueryDict`` fornisce i seguenti metodi: |
| | 478 | |
| | 479 | .. |
| | 480 | * ``copy()`` -- Returns a copy of the object, using ``copy.deepcopy()`` |
| | 481 | from the Python standard library. The copy will be mutable -- that is, |
| | 482 | you can change its values. |
| | 483 | |
| | 484 | * ``copy()`` -- Restituisce una copia dell'oggetto generata usando |
| | 485 | ``copy.deepcopy()`` fornito dalla libreria standard di Pyhton. La copia |
| | 486 | sarà mutabile -- ovvero, i valori potranno essere modificati. |
| | 487 | |
| | 488 | .. |
| | 489 | * ``getlist(key)`` -- Returns the data with the requested key, as a Python |
| | 490 | list. Returns an empty list if the key doesn't exist. It's guaranteed to |
| | 491 | return a list of some sort. |
| | 492 | |
| | 493 | * ``getlist(key)`` -- Restituisce i dati assieme alla chiave (key), sottoforma |
| | 494 | di lista Python. Se la chiave non esiste viene restituita una lista |
| | 495 | vuota. Usando questo metodo è garantito che il risultato sia comunque una |
| | 496 | lista. |
| | 497 | |
| | 498 | .. |
| | 499 | * ``setlist(key, list_)`` -- Sets the given key to ``list_`` (unlike |
| | 500 | ``__setitem__()``). |
| | 501 | |
| | 502 | * ``setlist(key, list_)`` -- Imposta la chiave (key) al valore ``list_`` |
| | 503 | (diversamente da ``__setitem__()``). |
| | 504 | |
| | 505 | .. |
| | 506 | * ``appendlist(key, item)`` -- Appends an item to the internal list |
| | 507 | associated with key. |
| | 508 | |
| | 509 | * ``appendlist(key, item)`` -- Accoda un elemento (item) alla lista associata |
| | 510 | alla chiave (key). |
| | 511 | |
| | 512 | .. |
| | 513 | * ``setlistdefault(key, default_list)`` -- Just like ``setdefault``, except |
| | 514 | it takes a list of values instead of a single value. |
| | 515 | |
| | 516 | * ``setlistdefault(key, default_list)`` -- Equivalente al metodo |
| | 517 | ``setdefault``, fatto salvo che ammette una lista (default_list) invece |
| | 518 | di un singolo valore. |
| | 519 | |
| | 520 | .. |
| | 521 | * ``lists()`` -- Like ``items()``, except it includes all values, as a list, |
| | 522 | for each member of the dictionary. For example:: |
| | 523 | |
| | 524 | >>> q = QueryDict('a=1&a=2&a=3') |
| | 525 | >>> q.lists() |
| | 526 | [('a', ['1', '2', '3'])] |
| | 527 | |
| | 528 | * ``lists()`` -- funziona come ``items()``, ma vengono inclusi tutti i |
| | 529 | valori, in forma di lista, per ogni elemento del dizionario. Ad esempio:: |
| | 530 | |
| | 531 | >>> q = QueryDict('a=1&a=2&a=3') |
| | 532 | >>> q.lists() |
| | 533 | [('a', ['1', '2', '3'])] |
| | 534 | |
| | 535 | .. |
| | 536 | * ``urlencode()`` -- Returns a string of the data in query-string format. |
| | 537 | Example: ``"a=2&b=3&b=5"``. |
| | 538 | |
| | 539 | * ``urlencode()`` -- Restituisce una stringa dei dati sottoforma di |
| | 540 | query-string. |
| | 541 | Ad esempio: ``"a=2&b=3&b=5"``. |
| | 542 | |
| | 543 | .. |
| | 544 | Examples |
| | 545 | -------- |
| | 546 | |
| | 547 | Esempi |
| | 548 | ------ |
| | 549 | |
| | 550 | .. |
| | 551 | Here's an example HTML form and how Django would treat the input:: |
| | 552 | |
| | 553 | <form action="/foo/bar/" method="post"> |
| | 554 | <input type="text" name="your_name" /> |
| | 555 | <select multiple="multiple" name="bands"> |
| | 556 | <option value="beatles">The Beatles</option> |
| | 557 | <option value="who">The Who</option> |
| | 558 | <option value="zombies">The Zombies</option> |
| | 559 | </select> |
| | 560 | <input type="submit" /> |
| | 561 | </form> |
| | 562 | |
| | 563 | Questo è un esempio di form HTML e di come Django tratterebbe gli input:: |
| | 564 | |
| | 565 | <form action="/foo/bar/" method="post"> |
| | 566 | <input type="text" name="your_name" /> |
| | 567 | <select multiple="multiple" name="bands"> |
| | 568 | <option value="beatles">The Beatles</option> |
| | 569 | <option value="who">The Who</option> |
| | 570 | <option value="zombies">The Zombies</option> |
| | 571 | </select> |
| | 572 | <input type="submit" /> |
| | 573 | </form> |
| | 574 | |
| | 575 | .. |
| | 576 | If the user enters ``"John Smith"`` in the ``your_name`` field and selects both |
| | 577 | "The Beatles" and "The Zombies" in the multiple select box, here's what |
| | 578 | Django's request object would have:: |
| | 579 | |
| | 580 | >>> request.GET |
| | 581 | {} |
| | 582 | >>> request.POST |
| | 583 | {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']} |
| | 584 | >>> request.POST['your_name'] |
| | 585 | 'John Smith' |
| | 586 | >>> request.POST['bands'] |
| | 587 | 'zombies' |
| | 588 | >>> request.POST.getlist('bands') |
| | 589 | ['beatles', 'zombies'] |
| | 590 | >>> request.POST.get('your_name', 'Adrian') |
| | 591 | 'John Smith' |
| | 592 | >>> request.POST.get('nonexistent_field', 'Nowhere Man') |
| | 593 | 'Nowhere Man' |
| | 594 | |
| | 595 | Se l'utente inserisce ``"John Smith"`` nel campo ``your_name`` e sceglie sia |
| | 596 | "The Beatles" che "The Zombies" dalla select box a scelta multipla, la |
| | 597 | richiesta si presenterebbe in questo modo:: |
| | 598 | |
| | 599 | >>> request.GET |
| | 600 | {} |
| | 601 | >>> request.POST |
| | 602 | {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']} |
| | 603 | >>> request.POST['your_name'] |
| | 604 | 'John Smith' |
| | 605 | >>> request.POST['bands'] |
| | 606 | 'zombies' |
| | 607 | >>> request.POST.getlist('bands') |
| | 608 | ['beatles', 'zombies'] |
| | 609 | >>> request.POST.get('your_name', 'Adrian') |
| | 610 | 'John Smith' |
| | 611 | >>> request.POST.get('nonexistent_field', 'Nowhere Man') |
| | 612 | 'Nowhere Man' |
| | 613 | |
| | 614 | .. |
| | 615 | Implementation notes |
| | 616 | -------------------- |
| | 617 | |
| | 618 | Note sull'implementazione |
| | 619 | ------------------------- |
| | 620 | |
| | 621 | .. |
| | 622 | The ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``, |
| | 623 | ``raw_post_data`` and ``user`` attributes are all lazily loaded. That means |
| | 624 | Django doesn't spend resources calculating the values of those attributes until |
| | 625 | your code requests them. |
| | 626 | |
| | 627 | Al fine di ottimizzare l'utilizzo delle risorse disponibili, i valori degli |
| | 628 | attributi ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``, |
| | 629 | ``raw_post_data`` e ``user`` vengono caricati soltanto nel momento in cui |
| | 630 | ne è richiesto l'utilizzo da parte del codice. |
| | 631 | |
| | 632 | .. |
| | 633 | HttpResponse objects |
| | 634 | ==================== |
| | 635 | |
| | 636 | Oggetti HttpResponse |
| | 637 | ==================== |
| | 638 | |
| | 639 | .. |
| | 640 | In contrast to ``HttpRequest`` objects, which are created automatically by |
| | 641 | Django, ``HttpResponse`` objects are your responsibility. Each view you write |
| | 642 | is responsible for instantiating, populating and returning an ``HttpResponse``. |
| | 643 | |
| | 644 | Diversamente dagli oggetti ``HttpRequest``, creati automaticamente da |
| | 645 | Django, gli oggetti ``HttpResponse`` sono una tua responsabilità. Devi |
| | 646 | prevedere che qualsiasi view che scrivi istanzi, popoli e restituisca un |
| | 647 | ``HttpResponse``. |
| | 648 | |
| | 649 | .. The ``HttpResponse`` class lives at ``django.http.HttpResponse``. |
| | 650 | |
| | 651 | La classe ``HttpResponse`` si trova in ``django.http.HttpResponse``. |
| | 652 | |
| | 653 | .. |
| | 654 | Usage |
| | 655 | ----- |
| | 656 | |
| | 657 | Utilizzo |
| | 658 | -------- |
| | 659 | |
| | 660 | .. |
| | 661 | Passing strings |
| | 662 | ~~~~~~~~~~~~~~~ |
| | 663 | |
| | 664 | Passaggio di stringhe |
| | 665 | ~~~~~~~~~~~~~~~~~~~~~ |
| | 666 | |
| | 667 | .. |
| | 668 | Typical usage is to pass the contents of the page, as a string, to the |
| | 669 | ``HttpResponse`` constructor:: |
| | 670 | |
| | 671 | >>> response = HttpResponse("Here's the text of the Web page.") |
| | 672 | >>> response = HttpResponse("Text only, please.", mimetype="text/plain") |
| | 673 | |
| | 674 | La tipica situazione di utilizzo è il passaggio dei contenuti di una pagina, |
| | 675 | come stringa, al costruttore dell'oggetto ``HttpResponse``:: |
| | 676 | |
| | 677 | >>> response = HttpResponse("Questo è il testo della pagina Web.") |
| | 678 | >>> response = HttpResponse("Soltanto testo, per cortesia.", mimetype="text/plain") |
| | 679 | |
| | 680 | .. |
| | 681 | But if you want to add content incrementally, you can use ``response`` as a |
| | 682 | file-like object:: |
| | 683 | |
| | 684 | >>> response = HttpResponse() |
| | 685 | >>> response.write("<p>Here's the text of the Web page.</p>") |
| | 686 | >>> response.write("<p>Here's another paragraph.</p>") |
| | 687 | |
| | 688 | Se vuoi aggiungere contenuti in modo incrementale, puoi usare ``response`` come |
| | 689 | fosse un oggetto file:: |
| | 690 | |
| | 691 | >>> response = HttpResponse() |
| | 692 | >>> response.write("<p>Questo è il testo della pagina Web.</p>") |
| | 693 | >>> response.write("<p>Questo è un altro paragrafo.</p>") |
| | 694 | |
| | 695 | .. |
| | 696 | You can add and delete headers using dictionary syntax:: |
| | 697 | |
| | 698 | >>> response = HttpResponse() |
| | 699 | >>> response['X-DJANGO'] = "It's the best." |
| | 700 | >>> del response['X-PHP'] |
| | 701 | >>> response['X-DJANGO'] |
| | 702 | "It's the best." |
| | 703 | |
| | 704 | Puoi inserire nuovi header o effettuare rimozioni usando la sintassi valida |
| | 705 | per i dizionari:: |
| | 706 | |
| | 707 | >>> response = HttpResponse() |
| | 708 | >>> response['X-DJANGO'] = "E' il migliore." |
| | 709 | >>> del response['X-PHP'] |
| | 710 | >>> response['X-DJANGO'] |
| | 711 | "E' il migliore." |
| | 712 | |
| | 713 | .. Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist. |
| | 714 | |
| | 715 | Nota che ``del`` non solleva un ``KeyError`` se l'header non esiste. |
| | 716 | |
| | 717 | .. |
| | 718 | Passing iterators |
| | 719 | ~~~~~~~~~~~~~~~~~ |
| | 720 | |
| | 721 | Passaggio di iteratori |
| | 722 | ~~~~~~~~~~~~~~~~~~~~~~ |
| | 723 | |
| | 724 | .. |
| | 725 | Finally, you can pass ``HttpResponse`` an iterator rather than passing it |
| | 726 | hard-coded strings. If you use this technique, follow these guidelines: |
| | 727 | |
| | 728 | * The iterator should return strings. |
| | 729 | * If an ``HttpResponse`` has been initialized with an iterator as its |
| | 730 | content, you can't use the ``HttpResponse`` instance as a file-like |
| | 731 | object. Doing so will raise ``Exception``. |
| | 732 | |
| | 733 | Invece di passare stringhe predefinite, ad ``HttpResponse`` puoi passare |
| | 734 | un iteratore. Se intendi utilizzare questa tecnica attieniti alle seguenti |
| | 735 | direttive: |
| | 736 | |
| | 737 | * L'iteratore deve restituire stringhe. |
| | 738 | * Se un oggetto ``HttpResponse`` è stato inizializzato con un iteratore |
| | 739 | come suo contenuto, non potrai usare le sue istanze come oggetti |
| | 740 | "file-like". Ciò solleverebbe un'eccezione. |
| | 741 | |
| | 742 | .. |
| | 743 | Methods |
| | 744 | ------- |
| | 745 | |
| | 746 | Metodi |
| | 747 | ------ |
| | 748 | |
| | 749 | .. |
| | 750 | ``__init__(content='', mimetype=DEFAULT_MIME_TYPE)`` |
| | 751 | Instantiates an ``HttpResponse`` object with the given page content (a |
| | 752 | string) and MIME type. The ``DEFAULT_MIME_TYPE`` is ``'text/html'``. |
| | 753 | |
| | 754 | ``content`` can be an iterator or a string. If it's an iterator, it should |
| | 755 | return strings, and those strings will be joined together to form the |
| | 756 | content of the response. |
| | 757 | |
| | 758 | ``__init__(content='', mimetype=DEFAULT_MIME_TYPE)`` |
| | 759 | Istanzia un oggeto ``HttpResponse`` con il contenuto della pagina come |
| | 760 | stringa (content) e un tipo MIME (mimetype). Il tipo MIME predefinito, |
| | 761 | ``DEFAULT_MIME_TYPE`` è ``'text/html'``. |
| | 762 | |
| | 763 | ``content`` può essere un iteratore o una stringa. Nel caso sia un |
| | 764 | iteratore, ci si aspetta che restituisca stringhe, che saranno in seguito |
| | 765 | unite e per diventare il contenuto della risposta. |
| | 766 | |
| | 767 | .. |
| | 768 | ``__setitem__(header, value)`` |
| | 769 | Sets the given header name to the given value. Both ``header`` and |
| | 770 | ``value`` should be strings. |
| | 771 | |
| | 772 | ``__setitem__(header, value)`` |
| | 773 | Imposta un valore per l'header specificato. E' richiesto che ``header`` e |
| | 774 | ``value`` siano stringhe. |
| | 775 | |
| | 776 | .. |
| | 777 | ``__delitem__(header)`` |
| | 778 | Deletes the header with the given name. Fails silently if the header |
| | 779 | doesn't exist. Case-sensitive. |
| | 780 | |
| | 781 | ``__delitem__(header)`` |
| | 782 | Rimuove l'header specificato. Se l'header è inesistente non vengono |
| | 783 | segnalati errori. Distingue lettere maiuscole da lettere minuscole. |
| | 784 | |
| | 785 | .. |
| | 786 | ``__getitem__(header)`` |
| | 787 | Returns the value for the given header name. Case-sensitive. |
| | 788 | |
| | 789 | ``__getitem__(header)`` |
| | 790 | Restituisce il valore dell'header specificato. Distingue lettere maiuscole |
| | 791 | da lettere minuscole. |
| | 792 | |
| | 793 | .. |
| | 794 | ``has_header(header)`` |
| | 795 | Returns ``True`` or ``False`` based on a case-insensitive check for a |
| | 796 | header with the given name. |
| | 797 | |
| | 798 | ``has_header(header)`` |
| | 799 | Restituisce ``True`` o ``False`` sulla base dell'esistenza dell'header |
| | 800 | specificato. Non vi è distinzione tra lettere maiuscole e lettere minuscole. |
| | 801 | |
| | 802 | .. |
| | 803 | ``set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)`` |
| | 804 | Sets a cookie. The parameters are the same as in the `cookie Morsel`_ |
| | 805 | object in the Python standard library. |
| | 806 | |
| | 807 | * ``max_age`` should be a number of seconds, or ``None`` (default) if |
| | 808 | the cookie should last only as long as the client's browser session. |
| | 809 | * ``expires`` should be a string in the format |
| | 810 | ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``. |
| | 811 | * Use ``domain`` if you want to set a cross-domain cookie. For example, |
| | 812 | ``domain=".lawrence.com"`` will set a cookie that is readable by |
| | 813 | the domains www.lawrence.com, blogs.lawrence.com and |
| | 814 | calendars.lawrence.com. Otherwise, a cookie will only be readable by |
| | 815 | the domain that set it. |
| | 816 | |
| | 817 | .. _`cookie Morsel`: http://www.python.org/doc/current/lib/morsel-objects.html |
| | 818 | |
| | 819 | ``set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)`` |
| | 820 | Imposta un cookie. I parametri sono gli stessi che si trovano nell'oggetto |
| | 821 | `cookie Morsel`_ nella libreria standard di Python. |
| | 822 | |
| | 823 | * ``max_age`` specifica un numero di secondi, o ``None`` (impostazione |
| | 824 | predefinita) se è previsto che il cookie venga mantenuto per tutta la |
| | 825 | durata della sessione di navigazione dell'utente (chiusura del browser). |
| | 826 | * ``expires`` specifica una stringa nel formato ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``. |
| | 827 | * Usa il parametro ``domain`` se vuoi impostare un cookie cross-domain. |
| | 828 | Ad esempio, ``domain=".lawrence.com"`` ha l'effetto di impostare un |
| | 829 | cookie leggibile dai domini www.lawrence.com, blogs.lawrence.com e |
| | 830 | calendars.lawrence.com. Non impostando il valore di domain il cookie sarebbe |
| | 831 | leggibile soltanto dal dominio che ne ha originato la creazione. |
| | 832 | |
| | 833 | .. _`cookie Morsel`: http://www.python.org/doc/current/lib/morsel-objects.html |
| | 834 | |
| | 835 | .. |
| | 836 | ``delete_cookie(key)`` |
| | 837 | Deletes the cookie with the given key. Fails silently if the key doesn't |
| | 838 | exist. |
| | 839 | |
| | 840 | ``delete_cookie(key)`` |
| | 841 | Elimina il cookie con la chiave specificata (key). Se la chiave è |
| | 842 | inesistente non vengono segnalati errori. |
| | 843 | |
| | 844 | .. |
| | 845 | ``content`` |
| | 846 | Returns the content as a Python string, encoding it from a Unicode object |
| | 847 | if necessary. Note this is a property, not a method, so use ``r.content`` |
| | 848 | instead of ``r.content()``. |
| | 849 | |
| | 850 | ``content`` |
| | 851 | Restituisce il contenuto come stringa Python, eseguendo l'encoding Unicode |
| | 852 | se necessario. Nota che ``content`` è una proprietà, non un metodo, perciò usa |
| | 853 | ``r.content`` invece di ``r.content()``. |
| | 854 | |
| | 855 | .. |
| | 856 | ``write(content)``, ``flush()`` and ``tell()`` |
| | 857 | These methods make an ``HttpResponse`` instance a file-like object. |
| | 858 | |
| | 859 | ``write(content)``, ``flush()`` e ``tell()`` |
| | 860 | Questi metodi rendono un'istanza ``HttpResponse`` un oggetto file-like. |
| | 861 | |
| | 862 | .. |
| | 863 | HttpResponse subclasses |
| | 864 | ----------------------- |
| | 865 | |
| | 866 | Sottoclassi di HttpResponse |
| | 867 | --------------------------- |
| | 868 | |
| | 869 | .. |
| | 870 | Django includes a number of ``HttpResponse`` subclasses that handle different |
| | 871 | types of HTTP responses. Like ``HttpResponse``, these subclasses live in |
| | 872 | ``django.http``. |
| | 873 | |
| | 874 | Django include alcune sottoclassi di ``HttpResponse`` adatte a fornire |
| | 875 | differenti tipologie di risposte HTTP. Come per ``HttpResponse``, queste |
| | 876 | sottoclassi si trovano in ``django.http``. |
| | 877 | |
| | 878 | .. |
| | 879 | ``HttpResponseRedirect`` |
| | 880 | The constructor takes a single argument -- the path to redirect to. This |
| | 881 | can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or an |
| | 882 | absolute URL with no domain (e.g. ``'/search/'``). Note that this returns |
| | 883 | an HTTP status code 302. |
| | 884 | |
| | 885 | ``HttpResponseRedirect`` |
| | 886 | Il costruttore accetta un solo argomento -- il percorso di redirezione, |
| | 887 | come URL completamente specificato (ad esempio, |
| | 888 | ``'http://www.yahoo.com/search/'``) o come URL assoluto senza dominio (ad |
| | 889 | esempio, ``'/search/'``). Nota che il codice di stato HTTP restituito è 302. |
| | 890 | |
| | 891 | .. |
| | 892 | ``HttpResponsePermanentRedirect`` |
| | 893 | Like ``HttpResponseRedirect``, but it returns a permanent redirect (HTTP |
| | 894 | status code 301) instead of a "found" redirect (status code 302). |
| | 895 | |
| | 896 | ``HttpResponsePermanentRedirect`` |
| | 897 | Funziona come ``HttpResponseRedirect``, ma restituisce uno stato di |
| | 898 | redirezione permanente (codice HTTP 301) invece di un redirect con codice |
| | 899 | 302. |
| | 900 | |
| | 901 | .. |
| | 902 | ``HttpResponseNotModified`` |
| | 903 | The constructor doesn't take any arguments. Use this to designate that a |
| | 904 | page hasn't been modified since the user's last request. |
| | 905 | |
| | 906 | ``HttpResponseNotModified`` |
| | 907 | Il costruttore non prevede alcun argomento. Usa questo tipo di risposta per |
| | 908 | indicare che una pagina non è stata modificata dall'ultima richiesta |
| | 909 | dell'utente. |
| | 910 | |
| | 911 | .. |
| | 912 | ``HttpResponseNotFound`` |
| | 913 | Acts just like ``HttpResponse`` but uses a 404 status code. |
| | 914 | |
| | 915 | ``HttpResponseNotFound`` |
| | 916 | Si comporta come ``HttpResponse`` ma usa il codice di stato 404. |
| | 917 | |
| | 918 | .. |
| | 919 | ``HttpResponseForbidden`` |
| | 920 | Acts just like ``HttpResponse`` but uses a 403 status code. |
| | 921 | |
| | 922 | ``HttpResponseForbidden`` |
| | 923 | Si comporta come ``HttpResponse`` ma usa il codice di stato 403. |
| | 924 | |
| | 925 | .. |
| | 926 | ``HttpResponseGone`` |
| | 927 | Acts just like ``HttpResponse`` but uses a 410 status code. |
| | 928 | |
| | 929 | ``HttpResponseGone`` |
| | 930 | Si comporta come ``HttpResponse`` ma usa il codice di stato 410. |
| | 931 | |
| | 932 | .. |
| | 933 | ``HttpResponseServerError`` |
| | 934 | Acts just like ``HttpResponse`` but uses a 500 status code. |
| | 935 | |
| | 936 | ``HttpResponseServerError`` |
| | 937 | Si comporta come ``HttpResponse`` ma usa il codice di stato 500. |
| | 938 | |
| | 939 | }}} |