i want the client to pass aditional information while loggin in to FastApi. I think for that i have to change the scheme for OAuth2PasswordRequestForm. Can anyone explain how to do that?
Im using the code from the FastApi tutorial right now:
https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/
If I understand your question correctly, you would like to have the user pass the info required by OAuth2PasswordRequestForm and also include some extra required information.
The easiest way to do this would probably be to create your own scheme that is a subclass of OAuth2PasswordRequestForm.
import fastapi
from fastapi import Depends
from fastapi.security import OAuth2PasswordRequestForm
app = fastapi.FastAPI()
class ExtendedOAuth2PasswordRequestForm(OAuth2PasswordRequestForm):
extra_data_field: str
#app.post("/your_endpoint")
def login_for_access_token(form_data: ExtendedOAuth2PasswordRequestForm = Depends()):
#do stuff with all of the normal OAuth2PasswordRequestForm and your extra data field...
You can add extend parameter to body request as follow:
And add the parameter to form data in frontend part:
Related
I have configured a dependencies.py where I'm injecting a set of dependencies to different services by using python's binder.bind(my_config). The goal is being able to easily inject those services to each endpoint of my API. The problem arises when I pass that service as an argument to my endpoint , after having injected that service via its name. So:
import inject
from fastapi import APIRouter, HTTPException, Request, Depends
from src.services.chords import ChordsService
router = APIRouter(prefix="/chords")
#router.get("")
#inject.params(chords_service=ChordsService)
def get_chords(chords_service: ChordsService, req: Request, key: str, suffix: str = None, instrument: str = None):
params = dict(req.query_params)
return chords_service.get(params)
This does not work. I've tried changing the order of get_chords' arguments. All I'm getting is different errors, but the one that appears the most is the following:
ChordsService is not a valid pydantic field type
I've read a bit about the use of pydantic in FastAPI and I see why I get this error, but I'm stuck at trying to inject those services. Is there a way to do it? Thanks!
You could use the dependency injection from fastapi directly. I don't have an IDE, so syntax is probably wrong, but you could do something like:
#lru_cache(max_size=1)
def get_chords_service():
return ChordsService()
#router.get("")
def get_chords(chords_service: ChordsService=Depends(get_chords_service), req: Request ...
This if you want the same ChordService instance everywhere.
If you are ok getting a new one each time, it becomes much simpler (you don't even need the getter function):
#router.get("")
def get_chords(chords_service: ChordsService=Depends(), req: Request ...
You can inject dependency to APIRouter like below -
router = APIRouter(prefix="/chords",
dependencies=[Depends(ChordsService)])
See Example: https://fastapi.tiangolo.com/tutorial/bigger-applications/#another-module-with-apirouter
I am new to web communication.
I use ubuntu and try to learn fastapi.
Let's say I post a file using curl. Seems to be common opinion that this is the best way to do it:
curl -F "file=#image1.jpg" http://127.0.0.1:8000/image -v
Now, on the server side I want to retrieve the image and add 1 to every pixel-value and then return it. But I have now idea how I "catch" the image from curl, how do I do that? Right now, I only have the the dummy function below which does not do anything intelligent:
#app.post("/image")
async def post_test():
print("I don't know how to catch the image :( ")
return {"You sent an image..."}
Please help with how I should write the post_test function! (Flask would work as well.)
You can check the full answer from my SO answer for a similar question (How to send file to fastapi endpoint using postman)
Basically, you would have to change your code to
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
#app.post("/file/")
async def create_upload_file(file: UploadFile = File(...)):
# Access your file object via file.file,
# and perform all the necessary transformations
# Return the filename, but you may return the file itself
return {"filename": file.filename}
I am using flask with mongoengine and Login Manager for session maintaining. I want to write test cases for authenticated views. can any one help/suggestions regarding this.
First off, I recommend using pytest, and the flask-pytest library which contains some great convenience features to make all of this easier.
flask-pytest comes out of the box with a client fixture, which, per the docs, refers to Flask.test_client
What you want to do is mimic a valid session (e.g. however you app is validating that a user is "logged in").
Here is how to do this without any supporting libraries:
import app
from flask import url_for
def test_authenticated_route():
app.testing = True
client = app.test_client()
with client.session_transaction() as sess:
# here you can assign whatever you need to
# emulate a "logged in" user...
sess["user"] = {"email": "test_user#example.com"}
# now, you can access "authenticated" endpoints
response = client.get(url_for(".protected_route"))
assert response.status_code == 200
This is also discussed in the Flask docs.
I have a RESTful API written in pyramid/cornice. It provides an API for an Ember client.
I have followed the cornice tutorial and have a valid_token validator which I use on many views as methods of resource classes.
def valid_token(request):
header = 'Authorization'
token = request.headers.get(header)
if token is None:
request.errors.add('headers', header, "Missing token")
request.errors.status = 401
return
session = DBSession.query(Session).get(token)
if not session:
request.errors.add('headers', header, "invalid token")
request.errors.status = 401
request.validated['session'] = session
Now I want to start selectively protecting resources. The Pyramid way seems to be to register authentication/authorization policies. The ACLAuthorizationPolicy seems to provide access to the nice ACL tooling in pyramid. However, it seems that pyramid needs both authentication and authorization policies to function. Since I'm authenticating with my validator this is confusing me.
Can I use ACL to control authorization whilst authenticating using my cornice valid_token validator? Do I need to register pyramid authentication or authorization policies?
I'm a bit confused, having little experience of using ACL in pyramid.
It is not an easy question :)
Shortly:
What you implemented in your validator is already taken care of by Pyramid with an AuthenticationPolicy
Start setting up a SessionAuthenticationPolicy with your custom callback (see code)
Once this authn setup, you will have those 401 responses, and your session value in the request.authenticated_userid attribute. You can also custom stuff in the request.registry object.
The only reason to keep your validator is if you want to return the invalid token messages in the 401 response. But for that, you can define a custom 401 pyramid view (using #forbidden_view_config)
Once you have that, you can setup a custom authorization for your views. You can find a very simple example in Cliquet first versions here : authz code and view perm
Good luck!
You may wanna do something like:
from pyramid.authentication import SessionAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from your_module import valid_token
authn_policy = SessionAuthenticationPolicy(debug=True, callback=valid_token)
authz_policy = ACLAuthorizationPolicy()
config = Configurator(authentication_policy=authn_policy,authorization_policy=authz_policy)
And ofcourse in the Configuration will receive other arguments like settigns, locale_negociator, ...........
Hope this will help
I know this is a duplicate question but by referring previous answers i couldn't find the solution yet.
I am using Google report api to fetch logs.
Please refer this link: https://developers.google.com/admin-sdk/reports/v1/libraries
Everything goes well and I am able to generate authorize URL using scope,client id etc.
But I am not able to redirect user to URL to fetch "code" from authorize URL.
I tried using webapp2 script but throws error = AssertionError: Request global variable is not set.
Here is the code I am using for redirection:
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
import ipdb;ipdb.set_trace()
path='my authorize url path'
return self.redirect(path) #throws error on this line
a1=MainPage() #object to call class
a2=a1.get() #call method of class
Where i am going wrong ? If webapp2 having standard bug for self.redirect, then which other framework can help to to perform same operation?
If i use app = webapp2.WSGIApplication([('/', MainPage)]) instead of creating objects then it doesnt even call get(self) function.
Any help would be appreciated.
Thanks.