Repository: sparckles/Robyn (language: python)

Issue:
add a set cookie interface in the response object
<!-- 
Thank you for considering improving Robyn!

Please describe your idea in depth. If you're not sure what to write, imagine the following:
  - How is this important to you? How would you use it?
  - Can you think of any alternatives?
  - Do you have any ideas about how it can be implemented? Are you willing/able to implement it? Do you need mentoring?
-->

Something like this

```python
@app.get("/cookie/")
def create_cookie():
    response = Response(....)
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return response
```


Discussion / hints:
@VishnuSanal , would you like to take this up in the coming week?
可以是这样的:
@app.get("/cookie/")
def create_cookie():
    response = Response(....)
    response.set_custom_header("cookie", "cookievalue") 
    #....set_custom_header("server_id","1")
    #....set_custom_header("server_id","2")
    #可以是通用的，用户自定义添加，设定。
    #return response   //自动返回，或者自动添加到response中,无需显示返回。
    return serve_html("./customheader.html")

request.get_custom_header("server_id","2")
@xiaojin20 , if it is just header , you should be able to do 
```
response.headers["server_id"]=2
```

I can double check again :D
&nbsp;File "/usr/local/lib/python3.11/dist-packages/robyn/router.py", line 131, in async_inner_handler
&nbsp; &nbsp; await handler(*args, **kwargs),
&nbsp; &nbsp; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
&nbsp; File "/root/www/website.py", line 122, in logindata
&nbsp; &nbsp; Response.headers["server_id"]=2
&nbsp; &nbsp; ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
&nbsp;TypeError: 'getset_descriptor' object does not support item assignment





---Original---
From: "Sanskar ***@***.***&gt;
Date: Sun, Jun 16, 2024 07:08 AM
To: ***@***.***&gt;;
Cc: ***@***.******@***.***&gt;;
Subject: Re: [sparckles/Robyn] add a set cookie interface in the responseobject (Issue #854)




 
@xiaojin20 , if it is just header , you should be able to do
 response.headers["server_id"]=2  
I can double check again :D
 
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you were mentioned.Message ID: ***@***.***&gt;
> @xiaojin20 , if it is just header , you should be able to do
> 
> ```
> response.headers["server_id"]=2
> ```
> 
> I can double check again :D

有完整简单，示例代码？？？？
@app.get("/response")
def gigiiggj(response:Response):
    response.headers["server_id"]="2"
    #headers ={}
    #up="files"
    #return Response(description=up, headers=headers, status_code=200)
    return response #<builtins.Request object at 0x7a5d867e10> ？？？？？发送失败！还是？
#获取自定义response server_1
@app.get('/')
def index(request):
    r=request.headers.get("server_id")#error 无法获取
    print(r)
    return "ok"

> 有完整简单，示例代码？？？？

Let me add some documentation and share it with you 😄 

Fix patch:
diff --git a/docs_src/src/pages/documentation/api_reference/getting_started.mdx b/docs_src/src/pages/documentation/api_reference/getting_started.mdx
index 213090689..717260d8a 100644
--- a/docs_src/src/pages/documentation/api_reference/getting_started.mdx
+++ b/docs_src/src/pages/documentation/api_reference/getting_started.mdx
@@ -523,6 +523,37 @@ Or setting the Headers globally *per* router.
   </Col>
 </Row>
 
+### Cookies
+
+<Row>
+<Col>
+Set cookies using the `set_cookies` function.
+</Col>
+<Col sticky>
+
+
+    <CodeGroup title="Request" tag="GET" label="/hello_world">
+
+    ```python {{ title: 'untyped' }}
+    @app.get("/")
+    def binary_output_response_sync(request):
+        response = Response(200, {'type': 'int'}, "desc")
+        response.set_cookie(key="fakesession", value="fake-cookie-session-value")
+        return response
+    ```
+
+    ```python {{title: 'typed'}}
+    from robyn import Request
+
+    @app.get("/")
+    def binary_output_response_sync(request: Request):
+        response = Response(200, {'type': 'int'}, "desc")
+        response.set_cookie(key="fakesession", value="fake-cookie-session-value")
+        return response
+    ```
+    </CodeGroup>
+  </Col>
+</Row>
 
 
 ## Request Headers
diff --git a/robyn/robyn.pyi b/robyn/robyn.pyi
index 948671e67..3e68a325d 100644
--- a/robyn/robyn.pyi
+++ b/robyn/robyn.pyi
@@ -293,6 +293,16 @@ class Response:
     response_type: Optional[str] = None
     file_path: Optional[str] = None
 
+    def set_cookie(self, key: str, value: str) -> None:
+        """
+
+        The function to set a cookie (onto headers).
+
+        @param key: the cookie name
+        @param value: the actual cookie value
+        """
+        pass
+
 class Server:
     def __init__(self) -> None:
         pass
diff --git a/src/types/response.rs b/src/types/response.rs
index 227d4147f..31962c581 100644
--- a/src/types/response.rs
+++ b/src/types/response.rs
@@ -156,4 +156,12 @@ impl PyResponse {
             .into_py(py);
         Ok(())
     }
+
+    pub fn set_cookie(&mut self, py: Python, key: &str, value: &str) -> PyResult<()> {
+        self.headers
+            .try_borrow_mut(py)
+            .expect("value already borrowed")
+            .append(key.to_string(), value.to_string());
+        Ok(())
+    }
 }


Test patch:
diff --git a/integration_tests/base_routes.py b/integration_tests/base_routes.py
index d60e84527..c99df7277 100644
--- a/integration_tests/base_routes.py
+++ b/integration_tests/base_routes.py
@@ -1,5 +1,4 @@
 import os
-
 import pathlib
 from collections import defaultdict
 from typing import Optional
@@ -530,6 +529,15 @@ async def async_raise():
     raise Exception()
 
 
+# cookie
+@app.get("/cookie")
+def cookie():
+    response = Response(status_code=200, headers=Headers({}), description="test cookies")
+    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
+
+    return response
+
+
 # --- POST ---
 
 # dict
diff --git a/integration_tests/test_get_requests.py b/integration_tests/test_get_requests.py
index a9ea1b67f..8afa15af9 100644
--- a/integration_tests/test_get_requests.py
+++ b/integration_tests/test_get_requests.py
@@ -61,3 +61,11 @@ def test_trailing_slash(session):
 
     r = requests.get("http://localhost:8080/trailing/")
     assert r.text == "Trailing slash test successful!"
+
+
+@pytest.mark.benchmark
+@pytest.mark.parametrize("key, value", [("fakesession", "fake-cookie-session-value")])
+def test_cookies(session, key, value):
+    response = get("/cookie", 200)
+
+    assert response.headers[key] == value