Tumgik
#postrequest
Photo
Tumblr media
Here’s a drawing I made of The Dumb Bunnies requested by @rockstarartistally!! I hope y’all enjoy this drawing!! #postrequest #thedumbbunnies #dumbbunnies #davpilkey #davpilkeybooks #happyoctober #happymonthofoctober #october #october2022 #2022 (at Los Angeles, California) https://www.instagram.com/p/CjRqfJvOsww/?igshid=NGJjMDIxMWI=
0 notes
gyuswhore · 1 year
Text
Lil reminder for everyone to READ THE PINNED POST
Requests are closed rn and I won’t be getting to any of the one’s being sent during this period until the next time I open requests. 
I’m still getting through asks sent before I closed them so if you sent one in during that time, just know I’m going through them it’s taking me a bit of time 
Thank you sm for interacting <3
2 notes · View notes
codehunter · 1 year
Text
How can I change a Django form field value before saving?
if request.method == 'POST': userf = UsersModelForm(request.POST) username = userf.data['username'] password = userf.data['password'] passwordrepeat = userf.data['passwordrepeat'] email = userf.data['email']
I tried this:
tempSalt = bcrypt.gensalt() password = bcrypt.hashpw(password,tempSalt) passwordrepeat = bcrypt.hashpw(passwordrepeat,tempSalt) userf.data['password'] = password userf.data['passwordrepeat'] = passwordrepeat
But i got error. How can i change the value of userf.data['password'] and userf.data['passwordrepeat'] before saving?
Error:
AttributeError at /registerThis QueryDict instance is immutableRequest Method: POSTRequest URL: http://127.0.0.1:8000/registerDjango Version: 1.3.1Exception Type: AttributeErrorException Value: This QueryDict instance is immutableException Location: /usr/local/lib/python2.6/dist-packages/django/http/__init__.py in _assert_mutable, line 359Python Executable: /usr/bin/pythonPython Version: 2.6.6Python Path: ['/home/user1/djangoblog', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/pymodules/python2.6/gtk-2.0']
https://codehunter.cc/a/django/how-can-i-change-a-django-form-field-value-before-saving
0 notes
deesoftservice · 3 years
Text
How to handle all request in express js
Role of routing is very important topic in nodejs. Many types of methods are given in nodejs for route like as (GET, POST, PUT, DELETE). 
1. Get
2. Post
3. Put
4. Delete
Get method for all get request handle
Post method for all post request handle
Put method for all put request handle
Delete method for all delete request handle
Four types of methods are most commonly used to create REST APIs.
http://deesoftservice.co.in/article/how-to-handle-all-request-in-express-js&47
Tumblr media
2 notes · View notes
vocalsynthp · 2 years
Note
Hi! Would you be able to add the kotonohas for synthv? It may be good to include their voiceroid / aivoice versions with kotonosync, since not many people know that tts voices can sing
Hi - we’re back from break! Thanks for your interest in the blog resources! We’ve added Kotonoha Aoi & Akane for Synthesizer V! (you can see that post here!) While we may add Voiceroid & A.I. Voice in the future, we are focusing on engines with native singing capability first! Each voice database receives its own post, so if we cover those software in the future, we will be sure to create new entries for Akane & Aoi!
2 notes · View notes
mrs-gucci · 3 years
Text
I bought myself TLD as a birthday present and I’m back on my Jacques bullshit...
and tomorrow’s Jacques day for my birthday week celebration, so feel free to send in your Jacques requests a bit early ;)
Tumblr media
>>birthday week post<<
>>requests FAQ<< **just a friendly reminder: all requests must be birthday-themed! non birthday-themed requests will not be accepted.**
26 notes · View notes
celestiagarden · 3 years
Text
Navigation post
Requests: open
Requesting rules
Masterlists
My Genshinsona
3 notes · View notes
hersan-posts · 3 years
Text
Nuevo método safe validation en Laravel
¿Qué pasa si quieres recuperar sólo una parte de los datos validados? ¿Cómo lo harías? para este tipo de casos se agrego al Form Request el método safe() que nos permite obtener una parte de los elementos validados.
Cuando validamos datos mediante el uso de un Form request o por medio del Request es posible recuperar los datos validados de forma muy sencilla. veamos como ejemplo el siguiente Form Request <?php namespace App\Http\Requests; class PostRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return…
Tumblr media
View On WordPress
1 note · View note
hackgit · 3 years
Text
xeca Project that creates encrypted #PowerShell payloads for offensive purposes. Creating...
xeca Project that creates encrypted #PowerShell payloads for offensive purposes. Creating position independent #shellcode from DLL files is also possible. https://github.com/postrequest/xeca
Tumblr media
GitHub - postrequest/xeca: PowerShell payload generator - GitHub PowerShell payload generator. Contribute to postrequest/xeca development by creating an account on GitHub.
0 notes
felord · 3 years
Text
CS50 project3-Single-page-app email client Solved
CS50 project3-Single-page-app email client Solved
Using JavaScript, HTML, and CSS, complete the implementation of your single-page-app email client. You must fulfill the following requirements: Send Mail: When a user submits the email composition form, add JavaScript code to actually send the email. You’ll likely want to make a POSTrequest to /emails, passing in values for recipients, subject, and body. Once the email has been sent, load the…
Tumblr media
View On WordPress
0 notes
electrogeekarg · 4 years
Link
Continuamos con la sección de entradas dedicadas al ESP8266. En esta ocasión nos toca ver cómo integrar la popular librería AXIOS para realizar peticiones AJAX desde un cliente web a un API REST servido desde el ESP8266.
Hace varias entradas que vimos cómo servir un API REST desde el ESP8266. Por su parte, en las dos últimas entradas hemos hecho un pequeño “paron” para ver los framework VueJS y Vuetify.
Por supuesto, el objetivo de las próximas entradas es integrar todos estos componentes para servir una aplicación en VueJS/Vuetify que comunique con un API REST servida desde el ESP8266. Así que en esta entrada veremos cómo realizar esta comunicación a través del API REST.
Para ello vamos a ver otro componente, la librería AXIOS, una popular librería en Javascript para realizar peticiones. AXIOS nos va a permitir hacer las peticiones AJAX en el cliente de una forma más “limpia”.
Anuncio:
Para ver su uso vamos a basarnos en la entrada en la que serviamos nuestro API REST de ejemplo, correctamente formateado, y vamos a adaptarla para ilustrar la comunicación con el cliente usando AXIOS. Lógicamente, el cambio respecto a esta entrada afecta principalmente al cliente, por lo que toda la parte backend no va a tener cambios.
Es decir, el programa principal del ESP8266 sigue siendo.
#include #include #include #include
#include “config.h” // Sustituir con datos de vuestra red #include “API.hpp” #include “Server.hpp” #include “ESP8266_Utils.hpp”
void setup(void) { Serial.begin(115200); SPIFFS.begin();
ConnectWiFi_STA();
InitServer(); }
void loop(void) { }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include
#include
#include
#include
  #include “config.h”  // Sustituir con datos de vuestra red
#include “API.hpp”
#include “Server.hpp”
#include “ESP8266_Utils.hpp”
  void setup(void)
{
   Serial.begin(115200);
   SPIFFS.begin();
       ConnectWiFi_STA();
       InitServer();
}
  void loop(void)
{
}
Así como la definición del servidor en el fichero ‘Server.hpp’.
AsyncWebServer server(80);
void notFound(AsyncWebServerRequest *request) { request->send(404, “text/plain”, “Not found”); }
void InitServer() { server.serveStatic(“/”, SPIFFS, “/”).setDefaultFile(“index.html”);
server.on(“/item”, HTTP_GET, getRequest); server.on(“/item”, HTTP_POST, [](AsyncWebServerRequest * request){}, NULL, postRequest); server.on(“/item”, HTTP_PUT, [](AsyncWebServerRequest * request){}, NULL, putRequest); server.on(“/item”, HTTP_PATCH, [](AsyncWebServerRequest * request){}, NULL, patchRequest); server.on(“/item”, HTTP_DELETE, deleteRequest);
server.onNotFound(notFound);
server.begin(); Serial.println(“HTTP server started”); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
AsyncWebServer server(80);
  void notFound(AsyncWebServerRequest *request) {
   request->send(404, “text/plain”, “Not found”);
}
  void InitServer()
{
   server.serveStatic(“/”, SPIFFS, “/”).setDefaultFile(“index.html”);
       server.on(“/item”, HTTP_GET, getRequest);
   server.on(“/item”, HTTP_POST, [](AsyncWebServerRequest * request){}, NULL, postRequest);
   server.on(“/item”, HTTP_PUT, [](AsyncWebServerRequest * request){}, NULL, putRequest);
   server.on(“/item”, HTTP_PATCH, [](AsyncWebServerRequest * request){}, NULL, patchRequest);
   server.on(“/item”, HTTP_DELETE, deleteRequest);
       server.onNotFound(notFound);
     server.begin();
    Serial.println(“HTTP server started”);
}
Y del API REST servido que tenemos definido en el fichero ‘API.hpp’.
#include “ESP8266_Utils_APIREST.hpp”
const char* PARAM_FILTER = “filter”;
void getAll(AsyncWebServerRequest *request) { String message = “Get All”; Serial.println(message); request->send(200, “text/plain”, message); }
void getFiltered(AsyncWebServerRequest *request) { String message = “Get filtered by ” + request->getParam(PARAM_FILTER)->value(); Serial.println(message); request->send(200, “text/plain”, message); }
void getById(AsyncWebServerRequest *request) { int id = GetIdFromURL(request, “/item/”);
String message = String(“Get by Id “) + id; Serial.println(message); request->send(200, “text/plain”, message); }
void getRequest(AsyncWebServerRequest *request) {
if (request->hasParam(PARAM_FILTER)) { getFiltered(request); } else if(request->url().indexOf(“/item/”) != -1) { getById(request); } else { getAll(request); } }
void postRequest(AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { String bodyContent = GetBodyContent(data, len);
StaticJsonDocument doc; DeserializationError error = deserializeJson(doc, bodyContent); if (error) { request->send(400); return;}
String string_data = doc[“data”]; String message = “Create ” + string_data; Serial.println(message); request->send(200, “text/plain”, message); }
void patchRequest(AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { int id = GetIdFromURL(request, “/item/”); String bodyContent = GetBodyContent(data, len);
StaticJsonDocument doc; DeserializationError error = deserializeJson(doc, bodyContent); if (error) { request->send(400); return;}
String string_data = doc[“data”]; String message = String(“Update “) + id + ” with ” + string_data; Serial.println(message); request->send(200, “text/plain”, message); }
void putRequest(AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { int id = GetIdFromURL(request, “/item/”); String bodyContent = GetBodyContent(data, len);
StaticJsonDocument doc; DeserializationError error = deserializeJson(doc, bodyContent); if (error) { request->send(400); return;}
String string_data = doc[“data”]; String message = String(“Replace “) + id + ” with ” + string_data; Serial.println(message); request->send(200, “text/plain”, message); }
void deleteRequest(AsyncWebServerRequest *request) { int id = GetIdFromURL(request, “/item/”);
String message = String(“Delete “) + id; Serial.println(message); request->send(200, “text/plain”, message); }
1
2
3
4
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
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
#include “ESP8266_Utils_APIREST.hpp”
  const char* PARAM_FILTER = “filter”;
  void getAll(AsyncWebServerRequest *request)
{
  String message = “Get All”;
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
  void getFiltered(AsyncWebServerRequest *request)
{
  String message = “Get filtered by “ + request->getParam(PARAM_FILTER)->value();
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
  void getById(AsyncWebServerRequest *request)
{
  int id = GetIdFromURL(request, “/item/”);
    String message = String(“Get by Id “) + id;
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
  void getRequest(AsyncWebServerRequest *request) {
     if (request->hasParam(PARAM_FILTER)) {
    getFiltered(request);
  }
  else if(request->url().indexOf(“/item/”) != –1)
  {
    getById(request);
  }
  else {
    getAll(request);
  }
}
  void postRequest(AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total)
{
  String bodyContent = GetBodyContent(data, len);
     StaticJsonDocument200> doc;
  DeserializationError error = deserializeJson(doc, bodyContent);
  if (error) { request->send(400); return;}
    String string_data = doc[“data”];
  String message = “Create “ + string_data;
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
  void patchRequest(AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total)
{
  int id = GetIdFromURL(request, “/item/”);
  String bodyContent = GetBodyContent(data, len);
     StaticJsonDocument200> doc;
  DeserializationError error = deserializeJson(doc, bodyContent);
  if (error) { request->send(400); return;}
    String string_data = doc[“data”];
  String message = String(“Update “) + id + ” with “ + string_data;
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
  void putRequest(AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total)
{
  int id = GetIdFromURL(request, “/item/”);
  String bodyContent = GetBodyContent(data, len);
     StaticJsonDocument200> doc;
  DeserializationError error = deserializeJson(doc, bodyContent);
  if (error) { request->send(400); return;}
    String string_data = doc[“data”];
  String message = String(“Replace “) + id + ” with “ + string_data;
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
  void deleteRequest(AsyncWebServerRequest *request) {
  int id = GetIdFromURL(request, “/item/”);
    String message = String(“Delete “) + id;
  Serial.println(message);
  request->send(200, “text/plain”, message);
}
Ahora vamos con el cliente, donde sí vamos a tener cambios importantes. El fichero ‘index.html’ cambia para incluir la librería AXIOS bien desde CDN (comentada) o desde la memoria del ESP8266.
ESP8266 Axios
Get All Get Filtered Get by Id
Create
Update
Replace
Delete
1
2
3
4
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
          ESP8266 Axios
      charset=“utf-8”>
      name=“viewport” content=“width=device-width, initial-scale=1.0”>
                                                onclick=“getAllRequest()”>Get All
                onclick=“getFilteredRequest()”>Get Filtered
                onclick=“getByIdRequest()”>Get by Id
                                          onclick=“postRequest()”>Create
                                          onclick=“patchRequest()”>Update
                                          onclick=“putRequest()”>Replace
                                          onclick=“deleteRequest()”>Delete
                                                         <span class="crayon-e ">type="text/javascript" src="./vendor/axios.min.js">
          <span class="crayon-e ">src="./js/API.js">
     Por otro lado, hemos externalizado todas las funciones de llamada a nuestro API REST en el fichero ‘API.js’, que contiene las funciones de ejemplo para las respectivas llamadas realizadas empleando la librería AXIOS.
function getAllRequest() { axios.get(‘item’) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
function getFilteredRequest() { axios.get(‘item’, { params: { filter : ‘myFilter’ } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
function getByIdRequest() { id = 10; axios.get(‘item/’ + id) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
function postRequest() { axios.post(‘item’, { data: ‘NewItem’ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
function putRequest() { id = 10; axios.put(‘item/’ + id, { data: ‘NewItem’ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
function patchRequest() { id = 10; axios.patch(‘item/’ + id, { data: ‘NewItem’ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
function deleteRequest() { id = 10; axios.delete(‘item/’ + id) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { }); }
1
2
3
4
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
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
function getAllRequest()
{
   axios.get(‘item’)
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
  function getFilteredRequest()
{
   axios.get(‘item’, {
      params: {
         filter : ‘myFilter’
      }
     })
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
  function getByIdRequest()
{
   id = 10;
   axios.get(‘item/’ + id)
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
  function postRequest()
{
   axios.post(‘item’, {
    �� data: ‘NewItem’
     })
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
  function putRequest()
{
   id = 10;
   axios.put(‘item/’ + id, {
      data: ‘NewItem’
     })
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
  function patchRequest()
{
   id = 10;
   axios.patch(‘item/’ + id, {
      data: ‘NewItem’
     })
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
  function deleteRequest()
{
   id = 10;
   axios.delete(‘item/’ + id)
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
      console.log(error);
     })
     .then(function () {
     });
}
Si cargamos todo en el ESP8266, y accedemos a la página web servida, veremos nuestra sencilla (y sí, feísima otra vez) interface para probar que conectamos correctamente con el API REST.
Si pulsamos en los distintos botones podremos comprobar como, efectivamente, el backend en el ES8266 recibe correctamente las peticiones y muestra los datos oportunos en la consola de comandos.
Como vemos, es muy sencillo integrar AXIOS en el ESP8266. Esta pequeña librería nos va a simplificar mucho el trabajo en nuestros proyectos, en especial al trabajar con API REST, haciendo nuestro código más sencillo y mantenible.
Por supuesto, es sólo un ejemplo para ilustrar la comunicación. En un proyecto real habría que definir el API REST, hacer el interface web completo, y hacer las acciones que queramos en el backend. Pero el ejemplo contiene todo el código necesario para hacer las peticiones CRUD (get/post/update/delete) tanto en backend como en frontend.
En las próximas dos entradas continuaremos mejorando este ejemplo, sobre todo la parte del interface web, añadiendo la integración del API REST y AXIOS a nuestras soluciones junto con VueJS y Vuetify ¡Hasta pronto! 
Descarga el código
Todo el código de esta entrada está disponible para su descarga en GitHub.
Si te ha gustado esta entrada y quieres leer más sobre ESP8266 puedes consultar la sección tutoriales de ESP8266
Anuncio:
0 notes
akubi0w1 · 4 years
Text
プリフライトリクエストの話
goのgorilla/muxという、ルーティング周りのパッケージを使ってメソッドを限定していたら、CORSに苦しめられた話。
結論いうと、
該当するエンドポイントにて、プリフライトリクエストのためにOPTIONSメソッドも許可してあげる必要があった。
何が起こったのか
フロントはlocalhost:3000、サーバはlocalhost:8080で動いている。
Reactで書いたフロントから、axiosでAPIサーバにアクセスした。 すると…
method: GETリクエストは普通に通る
method: POSTリクエストは以下エラーを吐かれる
// ブラウザで吐かれたエラー Access to XMLHttpRequest at 'http://localhost:8080/rooms' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
サーバの実装
// サーバ側の実装 func main() { ... // ルーティング部分 r := mux.NewRouter() ... r.HandleFunc("/rooms", apiFunc(roomHandler.GetAllRooms)).Methods("GET") // リクエストが通る r.HandleFunc("/rooms", apiFunc(roomHandler.CreateRoom)).Methods("POST") // リクエストが届かない } // エンドポイントで共通処理 func apiFunc(apiFunc http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Access-Control-Allow-Origin", "http://localhost:3000") w.Header().Add("Access-Control-Allow-Headers", "Content-Type,Accept,Origin") w.Header().Add("Access-Control-Allow-Credentials", "true") // プリフライトリクエストだった場合、後の処理を行わないために弾き飛ばす if r.Method == http.MethodOptions { return } w.Header().Add("Content-Type", "application/json") apiFunc(w, r) } }
クライアントの実装
// クライアント側の実装 // 実際はちょっと違うけどね const postRequest = name => { axios.post("http://localhost:8080/rooms", { name: name, }, { withCredentials: true, }).then(res => console.log(res)) .catch(err => console.log(err)); }
サーバ側の実装で、Access-Control-Allow-Originを設定しているから、リクエスト通るはずなんやけどなあ、と思っていた。そもそも原因はそこじゃなかった。
原因と解決
そもそもプリフライトリクエストをしっかり理解していなかったので整理。
プリフライトリクエスト is なに
実際の通信の前に権限確認のために送信するリクエスト
実際に行う通信が、サーバに許可されているか、されていないかを確認するために送信するリクエスト。 クライアント(ブラウザ)は、サーバに対し、プリフライトリクエストを送信する。その結果から、実際に送信しようとしていたリクエストが、通信可能かを判断する。 可能なら実際にリクエストをするし、可能でなかったらエラーを吐く。
以下条件を全て満たすリクエストは、simple cross-origin requestと呼ばれており、プリフライトリクエストを伴わない。
HTTPリクエストがシンプルメソッド(GET、POST、HEADのいずれか)
ヘッダーがシンプルヘッダー(Accept、Accept-Language、Content-Language、Content-Type)のみ
Content-Typeを含む場合、application/x-www-form-urlencoded、multipart/form-data、text-plainのいずれか
// プリフライトリクエストを伴うリクエストの通信フロー client server | | | ---------> | // プリフライトリクエスト。method: OPTIONS | <--------- | // res: サーバが許可する通信の内容(origin, headers, methods, etc...) | | | ---------> | // 実際のリクエスト。method: POST | <--------- | // res: 実際のレスポンス
今回の場合、Content-Typeがapplication/jsonなのでプリフライトリクエストが飛ぶ。
やったこと
紆余曲折はあったけど、確信つけたところだけ。
ブラウザにて通信の確認。 プリフライトリクエスト(method: OPTIONS)がmethod not allowedになっている。
Tumblr media
つまり、http://localhost:8080/roomsでは、OPTIONSメソッドが許可されてないってこと
なので、
// サーバ側の実装 func main() { ... // ルーティング部分 r := mux.NewRouter() ... r.HandleFunc("/rooms", apiFunc(roomHandler.GetAllRooms)).Methods("GET") r.HandleFunc("/rooms", apiFunc(roomHandler.CreateRoom)).Methods("POST", "OPTIONS") // OPTIONSも許可 }
これで無事、リクエストが飛んだ…
参考
Real World HTTP
0 notes
codehunter · 2 years
Text
User Registration with error: no such table: auth_user
I am trying to use Django's default Auth to handle register and log in.
setting.py:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books',)MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',)AUTH_USER_MODEL = 'books.User'
books.models.py:
class User(AbstractUser): account_balance = models.DecimalField(max_digits=5, decimal_places=2, default=0)
views.py:
from django.contrib.auth.forms import UserCreationFormdef register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/accounts/profile/") else: form = UserCreationForm() return render(request, "registration/register.html", {'form': form,})
urls.py:
urlpatterns = patterns('', (r'^accounts/login/$', login), (r'^accounts/logout/$', logout), (r'^accounts/profile/$', profile), (r'^accounts/register/$', register),)
I tried deleting the db.sqlite3 file and re-ran python manage.py syncdb but I still get this error message:
OperationalError at /accounts/register/no such table: auth_userRequest Method: POSTRequest URL: http://127.0.0.1:8000/accounts/register/Django Version: 1.7b4Exception Type: OperationalErrorException Value: no such table: auth_user
https://codehunter.cc/a/django/user-registration-with-error-no-such-table-auth-user
0 notes
deesoftservice · 3 years
Text
Post request send with complex raw data in express
how to send simple json raw and complex, nested row data in post request then how to received json data in express
1. select post request in postman.
2. click to body tab and select Json in the dropdown box.
3. Create raw data like as first_name, last_name, mobile_no, email, password
http://deesoftservice.co.in/article/post-request-send-with-complex-raw-data-in-express&48
Tumblr media
1 note · View note
knoldus · 7 years
Link
Finagle is an extensible RPC system for the JVM, used to construct high-concurrency servers. Finagle implements uniform client and server APIs for several protocols, and is designed for high performance and concurrency. Most of Finagle’s code is protocol agnostic, simplifying the implementation of new protocols.
Today here I am going to implement the Finagle example using Scala where I am sending the request with some message & get future of response using Finagle.
First, let’s define a service. Here we define a service to receive an HTTP request.
def apply(request: Request) = { request.method match { case Method.Post => request.uri match { case "/" => log.error("in post") val str = request.getContentString() //any business logic val response = Response(Version.Http11, Status.Ok) response.contentString = "Hello..!! " + str Future.value(response) case _ => log.error("REQUEST NOT FOUND") Future.value(Response(Version.Http11, Status.NotFound)) } case Method.Get => request.uri match { case "/" => val str = request.getContentString() //any business logic val response = Response(Version.Http11, Status.Ok) response.contentString = "Thank You " + str Future.value(response) case _ => log.error("REQUEST NOT FOUND") Future.value(Response(Version.Http11, Status.NotFound)) } } }
Here, we get the request. After that, we are simply matching what type of request it is either GET or POST. and request.uri tell us about the end-point of the request.
Then initiate and start our server.
import java.net.InetSocketAddress import com.twitter.finagle.Http import com.twitter.finagle.builder.{ Server, ServerBuilder } class ComputeServerBuilder { val response = new ComputeResponse val address = new InetSocketAddress(10000) def start: Server = ServerBuilder() .stack(Http.server) .bindTo(address) .name("HttpServer") .build(response) }
Last, let’s define a client to consume this server.
computeServerBuilder = new ComputeServerBuilder server = computeServerBuilder.start client = ClientBuilder() .stack(Http.client) .hosts(computeServerBuilder.address) .hostConnectionLimit(1) .build()
Now, we can send any number of requests using this client to our server.
Here, I made some test cases to hit the server can check either we are getting response successfully or not like shown below:-
val postRequest = Request(Version.Http11, Method.Post, "/") postRequest.setContentString("Knoldus") val postFutureResponse = client(postRequest).asScala postFutureResponse.map(response => println(response.getContentString())) postFutureResponse.map(response => assert(response.status === Status.Ok && response.contentString.contains("Knoldus")))
To run it by yourself you can also clone my sample example from my git repo.
When I start implementing the Finagle, the challenge that I face in using Finagle is in handling the future between two different API i.e. Scala & Twitter itself. To deal with this, I used some implicit conversion of futures between these two APIs. Code for the same is also available on repo.
To know about the core of Finagle you can also read this great blog: Finagle: Controlling the Future Of RPC systems which helps me a lot during my learnings.
References:
https://twitter.github.io/finagle/
https://www.youtube.com/results?search_query=twitter+finagle
0 notes
mrs-gucci · 3 years
Text
it’s Sackler day!
(and also, catch-up day)
Tumblr media
submit your Sackler requests and I’ll also (attempt to) finish up some Jacques and some Mauri requests as well.
>>birthday week post<<
>>requests FAQ<< **just a friendly reminder: all requests must be birthday-themed! non birthday-themed requests will not be accepted.**
(character Q’s for tomorrow’s Q & A are also being accepted today!)
19 notes · View notes