Django Unexpected 405 Response - python

Problem
My django application often respond 405 Method Now Allowed even though
it's working api on development environment. But if i restart
development server (python manage.py runserver) It works.
Environment
macOS Mojave 10.14
Python 3.6.4 (Isolated environment via Pipenv)
Django 2.1.4
djangorestframework 3.8.2
API Code
settings/urls.py (root url file)
from django.urls import path, include
import my_account.urls
urlpatterns = [
path('account/', include(my_account.urls, namespace='account_v1')),
]
my_account/urls.py
from django.urls import path
from .apps import MyAccountConfig
from .views import TokenView
app_name = MyAccountConfig.name
urlpatterns = [
path('token/', TokenView.as_view()),
]
my_account/views.py
from rest_framework.views import APIView
class TokenView(APIView):
def post(self, request):
# Some Business-Logic Code
pass
Log
Log when 405 occured
System check identified no issues (0 silenced).
December 07, 2018 - 11:22:54
Django version 2.1.4, using settings 'my_server.settings.staging'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
.env Applied
[07/Dec/2018 11:24:30] "OPTIONS /account/token/ HTTP/1.1" 200 0
[07/Dec/2018 11:24:30] "{"email":"email#hidden.com","password":"hidden_password"}POST /account/token/ HTTP/1.1" 405 66
Log when working
System check identified no issues (0 silenced).
December 07, 2018 - 11:48:01
Django version 2.1.4, using settings 'my_server.settings.staging'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
.env Applied
[07/Dec/2018 11:48:08] "OPTIONS /account/token/ HTTP/1.1" 200 0
[07/Dec/2018 11:48:09] "POST /account/token/ HTTP/1.1" 200 517
In chrome network tab, no difference between request for 200 and 405.

I Have faced this same error for the last two months eventually I Solved at the end.
Error:
When a user token is become expired we will be getting 401 status code with unauthorized message, when this happens the next API is also getting interrupted it returns 405 Method Not Allowed as an error.
Solution :
There was a bug issue in Django version 2.1 you have to upgrade your django version to 2.2.
After that check this error it will not raise.

HTTP_405_METHOD_NOT_ALLOWED
The status code 405 represents that you are requesting in a method that is not allowed.
Based on your code, You are defining Token API to be accessible by post method.
look at this log:
[07/Dec/2018 11:48:09] "POST /account/token/ HTTP/1.1" 200 517
in this you are sending clear POST request which will be ok. but look at the provided log for failed cases:
[07/Dec/2018 11:24:30] "{"email":"email#hidden.com","password":"hidden_password"}POST /v1/account/token/ HTTP/1.1" 405 66
1- For some reason in your UI, you are sending a request with method {"email":"email#hidden.com","password":"hidden_password"}POST!!!!.
2- and you are sending request to /v1/account/token/ API endpoint which is not registered in your urls at all (based on what info you gave us)

Related

How to logging Flask python endpoint actions in Spring Boot Admin?

I'm working in PyCharm and building endpoints with Flask, and I use Pyctuator as well. It is connected to a Spring Boot Admin Server, and I saw a lot of logs, which was unuseful for me, like:
2022-07-26 10:28:32,212 INFO 1 -- [Thread-17317] _internal: 172.18.0.1 - - [26/Jul/2022 10:28:32] "GET /actuator/loggers HTTP/1.1" 200 -
I turned off the loggers on the site, and I want to setup in PyCharm if the server do any processes with any endpoints, then send back messages, like: 'System started xy process', 'System stopped xy process.' etc.
Could you please help how can I set it up in PyCharm?
Thanks!

What do these numbers mean in my Flask application's log output?

I have a Flask application that runs with Flask-SocketIO. I recently installed eventlet in order to improve performance and utilise the web socket protocol.
My HTTP logs started having 2 additional parameters at the end (after the status code):
127.0.0.1 - - [26/Sep/2019 15:27:58] "GET /supported_countries HTTP/1.1" 200 488 0.019999
127.0.0.1 - - [26/Sep/2019 15:27:58] "GET /specializations HTTP/1.1" 200 381 0.003003
In this case it's the numbers 488 0.019999 and 381 0.003003.
I am assuming it's the size of the response and the time it took to complete the request?
What are they? (and can I configure what request info is logged?)
Here is my application.py
from my_app import create_app, socketio
app = create_app()
if __name__ == '__main__':
socketio.run(app, host=app.config.get('APP_HOST'),
log_output=app.config.get('LOGGING', False))
Again, please note that this was not happening prior to the installaiton of eventlet. Flask-SocketIO atuomatically detects that I have it installed and selects it (emphasis mine):
The extension automatically detects which asynchronous framework to use based on what is installed. Preference is given to eventlet, followed by gevent. For WebSocket support in gevent, uWSGI is preferred, followed by gevent-websocket. If neither eventlet nor gevent are installed, then the Flask development server is used.
So the Flask dev server does not output these numbers, whilst the eventlet-configured server does.

Error getting started with cloud endpoints on GAE

I'm just getting started with cloud endpoints by following the tutorial from
here.
Even when i copy paste the code exactly, I'm unable to look at the custom endpoin methods. When I run the project and type
http://localhost:8080/_ah/api/explorer
I get redirected to a blank api-explorer page. Here are the logs from the App Engine Launcher
INFO 2015-09-22 20:45:52,114 devappserver2.py:763] Skipping SDK update check.
INFO 2015-09-22 20:45:52,661 api_server.py:205] Starting API server at: http://localhost:53371
INFO 2015-09-22 20:45:52,676 dispatcher.py:197] Starting module "default" running at: http://localhost:8080`
INFO 2015-09-22 20:45:52,676 admin_server.py:118] Starting admin server at: http://localhost:8000
INFO 2015-09-22 20:46:08,792 module.py:808] default: "GET /_ah/api/explorer HTTP/1.1" 302 -
INFO 2015-09-22 20:46:12,805 module.py:808] default: "GET /_ah/api/explorer HTTP/1.1" 302 -
INFO 2015-09-22 20:46:17,711 module.py:808] default: "GET /_ah/api/static/proxy.html?jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.z0-pPDgHPQw.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCO4-ZDXf1JrE4AXDItAeFdjXKLW8w HTTP/1.1" 200 7690
The app.yaml and python files are exactly as described in the tutorial.
Can someone please tell me what exactly is going on and how to fix it.

Google App Engine deferred.defer() error 404

I'm trying to get running a task in the Task Queue using deferred.defer(). The task is added to the default task queue, but the task fail with a 404 error.
This is the handler:
import webapp2
import models
import defer_ajust_utils
from google.appengine.ext import ndb
from google.appengine.ext import deferred
class ajust_utils(webapp2.RequestHandler):
def get(self):
deferred.defer(defer_ajust_utils.DoTheJob)
application = webapp2.WSGIApplication([('/ajust_utils', ajust_utils)], debug=True)
This is the module defer_ajust_utils :
import logging
import models
from google.appengine.ext import ndb
def DoTheJob():
logging.info("Debut de la mise a jour des utilisateurs")
utilisateurs = models.Utilisateur.query()
utilisateurs = utilisateurs.fetch()
for utilisateur in utilisateurs:
utilisateur.produire_factures_i = False
utilisateur.put()
logging.info("Fin de la mise a jour des utilisateurs")
And my app.yaml file :
application: xxxx
version: dev
runtime: python27
api_version: 1
threadsafe: yes
builtins:
- deferred: on
handlers:
- url: /ajust_utils
script : tempo_ajuster_utils.application
login: admin
Here's the log :
0.1.0.2 - - [10/Mar/2014:17:50:45 -0700] "POST /_ah/queue/deferred HTTP/1.1" 404 113
"http://xxxx.appspot.com/ajust_utils" "AppEngine-Google;
(+http://code.google.com/appengine)" "xxxx.appspot.com" ms=6 cpu_ms=0
cpm_usd=0.000013 queue_name=default task_name=17914595085560382799
app_engine_release=1.9.0 instance=00c61b117c0b3648693af0563b92051423b3cb
Thank you for help!!
If you are using push-to-deploy with git, when you add in a 'builtin' part to the app.yaml, such as in
builtins:
- deferred: on
you need to do a 'normal' gcloud deploy before you run the app. Otherwise it will not update the running app, which causes 404 errors for /_ah/queue/deferred
There is an open bug for this, so vote for it and it may get fixed. https://code.google.com/p/googleappengine/issues/detail?id=10139
I was receiving the same error.
It appears to be a documentation defect with https://cloud.google.com/appengine/articles/deferred
I looked in the source code and found the following, which wasn't in any of the documentation:
In order for tasks to be processed, you need to set up the handler. Add the
following to your app.yaml handlers section:
handlers:
- url: /_ah/queue/deferred
script: $PYTHON_LIB/google/appengine/ext/deferred/handler.py
login: admin
As I have threadsafe: true set in my app.yaml, I had to add the following handler:
- url: /_ah/queue/deferred
script: google.appengine.ext.deferred.deferred.application
login: admin
and then the deferred task queue began working and stopped 404'ing.
I think you have to add the option deferred: on to your apps "builtin" options in the app.yaml Here is an excerpt from
https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Builtin_handlers
builtins:
- deferred: on
The following builtin handlers are available:
admin_redirect - For production App Engine, this results in a redirect from /_ah/admin to the admin console. This builtin has no effect in the development web server.
appstats - Enables Appstats at /_ah/stats/, which you can use to measure your application's performance. In order to use Appstats, you also need to install the event recorder.
deferred - Enables the deferred handler at /_ah/queue/deferred. This builtin allows developers to use deferred.defer() to simplify the creation of Task Queue tasks. Also see Background work with the deferred library.

Flask: getting random repeated flash messages when flash() is in #app.before_request

When i use flash() in #app.before_request, I get what seems like a random number of repeated entries. Refreshing the page over and over will give me between 1 and 4 repeated messages.
There aren't any redirects.
My code is simply:
if app.config['INSTANCE'] == 'DEV':
flash("This data is from the development DB")
Alternatively, I wasn't able to figure out how to access/modify the array of messages that flash() seems to append to other than in the template via get_flashed_messages(). Anyone know how?
You can access the list of waiting messages via flashes = session.get('_flashes', []). You can view the code on Github
On the note of why you're getting a few messages flashing, it's because you're making multiple requests (but probably don't know it). Your web-browser is probably asking for favicon.ico which is a request, so causes a flash, etc. If you're running in debug mode, your console window will show all the requests being handled. For example loading a simple flask example in Chrome causes this to show:
127.0.0.1 - - [21/Jun/2013 16:35:05] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Jun/2013 16:35:05] "GET /favicon.ico HTTP/1.1" 404 -
One is my request to view the homepage, the other is Chrome asking for the favicon (and it being told it doesn't exist).

Categories