Can someone tell me why SqlAlchemy is showing me this error.? - flask-sqlalchemy

Can anyone please where am i doing wrong?
Can anyone please where am i doing wrong?
Can anyone please where am i doing wrong?
Can anyone please where am i doing wrong?
#app.route("/userLogin", methods=['POST'])
def userLogin():
userr = request.json['email']
user = db.session.query(Users).filter_by(email=userr).first()
if user:
if bcrypt.hashpw(request.json['password'].encode('utf-8'), user[4]) == user[4]:
access_token = create_access_token(identity=request.json['email'])
user['tokens'].append({'token': str(access_token)})
db.session.add(user)
db.session.commit()
return jsonify(token=str(access_token)), 201
return jsonify(message='Invalid Username/Password'), 401
Error:
File "C:\Users\PROFESSOR\Desktop\WebDev Project\Back-end\ven\lib\site-packages\flask\app.py",
line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "c:\Users\PROFESSOR\Desktop\WebDev Project\Back-end\Api\views.py", line 60, in userLogin
if bcrypt.hashpw(request.json['password'].encode('utf-8'), user[4]) == user[4]:
TypeError: 'Users' object is not subscriptable

In your code, you are treating the user object like a dictionary and trying to add or use values from it. You cant do that.
You shouldnt use user[4] or any other such subscripting of user object in your code.
#app.route("/userLogin", methods=['POST'])
def userLogin():
userr = request.json['email']
user = db.session.query(Users).filter_by(email=userr).first()
if user:
if bcrypt.hashpw(request.json['password'].encode('utf-8'), user[4]) ==
user[4]:
access_token = create_access_token(identity=request.json['email'])
user['tokens'].append({'token': str(access_token)})
db.session.add(user)
db.session.commit()
return jsonify(token=str(access_token)), 201
return jsonify(message='Invalid Username/Password'), 401

Related

I got error from calling json() when trying to running

Hello i want asking somethin that i got when i tried to run my streamlit, so i got error like this on my frontend page, i import it from backend page:
i will show my code too
Predict = st.button('Predict Satisfacion Rate')
if Predict:
r = requests.post(URL, json=data)
res = r.json()
if res['code'] == 200:
res2 = (res['result']['description'])
if res2 == 'Not Satisfied':
st.markdown('**The Passenger is not Satisfied**')
col4,col5,col6 = st.columns([1,1,1])
with col5 :
st.image('Happy.jpg')
else:
st.markdown('**The Passenger is Satisfied**')
col7,col8,col9 = st.columns([1,1,1])
with col8 :
st.image('NotHappy.jpg')
else:
st.write('**Error**')
st.write(f"Details : {res['result']['description']}")
so how can i do to solve this error?
thank you.
In your code, the conversion res = r.json() is unnecessary. Unless you really need this as JSON somewhere else, you can test the status code directly from the r object as r.status_code.
After if r.status_code == 200:, you can then convert to JSON if you really need to, as you should be confident that the server returned a valid response.

Flask - How can I use my functions on the URL

I'm starting to learn Flask and maybe I'm just using the wrong words to search, but here's the problem.
I have this class:
class Video(Resource):
#marshal_with(resource_fields)
def get(self, video_id):
result = VideoModel.query.filter_by(id=video_id).first()
if not result:
abort(404, message="Could not find video with that id")
return result
#marshal_with(resource_fields)
def put(self, video_id):
args = video_put_args.parse_args()
result = VideoModel.query.filter_by(id=video_id).first()
if result:
abort(409, message="Video id taken...")
video = VideoModel(id=video_id, name=args['name'], views=args['views'], likes=args['likes'])
db.session.add(video)
db.session.commit()
return video, 201
#marshal_with(resource_fields)
def patch(self, video_id):
args = video_update_args.parse_args()
result = VideoModel.query.filter_by(id=video_id).first()
if not result:
abort(404, message="Video doesn't exist, cannot update")
if args['name']:
result.name = args['name']
if args['views']:
result.views = args['views']
if args['likes']:
result.likes = args['likes']
db.session.commit()
return result
And I'm trying to make so when I have an URL like http://127.0.0.1/5000/video/put/1/Test/80/2, I can use the funtion from the URL by typing it. Is there any way to do this? Thanks in advance!

Karate framework variable usage

I have this steps:
...
Then status 200
And match response.requests[0].request.url == "/endpoint"
And json body = response.requests[0].request.body
And match body == { "something": "something"}
To simplify, I tried to put response.requests[0].request in a variable called request:
...
Then status 200
And def request = response.requests[0].request
And match request.url == "/endpoint"
And json body = request.body
And match body == { "something": "something"}
I'm having the following error:
'request' is not a variable, use the form '* request <expression>' instead
I read the documentation and the use of request seems to be fine:
Given def color = 'red '
And def num = 5
Then assert color + num == 'red 5'
What am I doing wrong?
Thanks in advance.
Just make this change:
* def req = response.requests[0].request
# other steps
* request req
We simply disallow def request (using request as a variable name) because a lot of newbie users get confused. The error message has worked 99.9% of the time for users to understand what the problem is, but I guess you fall in the 0.1% :)

Cant handle a response error on django-rest-framework

I am trying to return 400 bad requets response when a user with a company created tries to create another one on my API
I tried with a Response but it does not work, it seems that it does not enter on the if
class CompanyViewSet(generics.ListCreateAPIView):
serializer_class = CompanySerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return UserCompany.objects.filter(owner=self.request.user.id)
def perform_create(self, serializer):
queryset = UserCompany.objects.filter(owner=self.request.user.id)
if queryset.exists():
content = {'API response error:': 'Can have only a one company for every user'}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
else:
serializer.save(owner=self.request.user)
When I create a company in user that already has one returns state 200 but don't create it, I expected it to return state 400
Because perform_create only save serializer . If you want control status response, you should override create. Try like this:
def create(self, request, *args, **kwargs):
queryset = UserCompany.objects.filter(owner=self.request.user.id)
if queryset.exists():
content = {'API response error:': 'Can have only a one company for every user'}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

apollo-upload-client and graphene-django

I have a question about using apollo-upload-client and graphene-django. Here I've discovered that apollo-upload-client adding operations to formData. But here graphene-django is only trying to get query parameter. And the question is, where and how it should be fixed?
If you're referring to the data that has a header like (when viewing the HTTP from Chrome tools):
Content-Disposition: form-data; name="operations"
and data like
{"operationName":"MyMutation","variables":{"myData"....}, "query":"mutation MyMutation"...},
the graphene-python library interprets this and assembles it into a query for you, inserting the variables and removing the file data from the query. If you are using Django, you can find all of the uploaded files in info.context.FILES when writing a mutation.
Here's my solution to support the latest apollo-upload-client (8.1). I recently had to revisit my Django code when I upgraded from apollo-upload-client 5.x to 8.x. Hope this helps.
Sorry I'm using an older graphene-django but hopefully you can update the mutation syntax to the latest.
Upload scalar type (passthrough, basically):
class Upload(Scalar):
'''A file upload'''
#staticmethod
def serialize(value):
raise Exception('File upload cannot be serialized')
#staticmethod
def parse_literal(node):
raise Exception('No such thing as a file upload literal')
#staticmethod
def parse_value(value):
return value
My upload mutation:
class UploadImage(relay.ClientIDMutation):
class Input:
image = graphene.Field(Upload, required=True)
success = graphene.Field(graphene.Boolean)
#classmethod
def mutate_and_get_payload(cls, input, context, info):
with NamedTemporaryFile(delete=False) as tmp:
for chunk in input['image'].chunks():
tmp.write(chunk)
image_file = tmp.name
# do something with image_file
return UploadImage(success=True)
The heavy lifting happens in a custom GraphQL view. Basically it injects the file object into the appropriate places in the variables map.
def maybe_int(s):
try:
return int(s)
except ValueError:
return s
class CustomGraphqlView(GraphQLView):
def parse_request_json(self, json_string):
try:
request_json = json.loads(json_string)
if self.batch:
assert isinstance(request_json,
list), ('Batch requests should receive a list, but received {}.').format(
repr(request_json))
assert len(request_json) > 0, ('Received an empty list in the batch request.')
else:
assert isinstance(request_json, dict), ('The received data is not a valid JSON query.')
return request_json
except AssertionError as e:
raise HttpError(HttpResponseBadRequest(str(e)))
except BaseException:
logger.exception('Invalid JSON')
raise HttpError(HttpResponseBadRequest('POST body sent invalid JSON.'))
def parse_body(self, request):
content_type = self.get_content_type(request)
if content_type == 'application/graphql':
return {'query': request.body.decode()}
elif content_type == 'application/json':
return self.parse_request_json(request.body.decode('utf-8'))
elif content_type in ['application/x-www-form-urlencoded', 'multipart/form-data']:
operations_json = request.POST.get('operations')
map_json = request.POST.get('map')
if operations_json and map_json:
operations = self.parse_request_json(operations_json)
map = self.parse_request_json(map_json)
for file_id, f in request.FILES.items():
for name in map[file_id]:
segments = [maybe_int(s) for s in name.split('.')]
cur = operations
while len(segments) > 1:
cur = cur[segments.pop(0)]
cur[segments.pop(0)] = f
logger.info('parse_body %s', operations)
return operations
else:
return request.POST
return {}