Issue updating an order with an authorized user(FastAPI) - fastapi

I don't know what I'm doing wrong here. I want to update an order with order id but I get TypeError: dict() takes exactly 1 positional argument (0 given). However, it worked fine when I updated a user.
#order_router.put('/update/{order_id}', response_model=Order_Pydantic)
async def update_by_order_id(order_id: str, order=OrderModel, Authorize: AuthJWT = Depends()):
try:
Authorize.jwt_required()
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORISED, detail='Invalid Token'
)
await Order.filter(id=order_id).update(**order.dict(exclude_unset=True))
return Order_Pydantic.from_queryset_single(Order.get(id=order_id))

I've seen where the error is coming from. I was using order=OrderModel instead of order: OrderModel

Related

throwing exception in let run clause is thrown when value is not null

I have a null safe operator block as follows, and if the value is null, I want to throw an exception. However, I'm experiencing that whether or not the value is null, the exception is thrown. The call to firebase returns Void, so does it get interpreted as null?
Firebase.auth.currentUser?.let { firebaseUser ->
Firebase.firestore.collection("mycollection")
.document("mycollectionid")
.collection("mychild")
.document("mychildid")
.set(data, SetOptions.merge())
.await()
} ?: run {
throw Exception("currentUser is null")
}
How can I make sure that I throw the error only if the let block doesn't execute?
let returns whatever the lambda returns. await() probably doesn't return anything, which is why the run is executed.
You probably want to replace let with also. This works the same as let except it returns whatever object it is called on instead of the lambda result.
See also Function selection

INDY Error 212 while executing createPairwise

I am trying to execute createPairwise function of indy-sdk package.
It throws an INDY Error 212 => WalletItemNotFound.
(I also executed createAndStoreMyDid function)
Here is my code
let [myDid, myVerkey] = await sdk.createAndStoreMyDid(await indy.wallet.get(), {});
let theirVerkey = await sdk.keyForDid(await indy.pool.get(), await indy.wallet.get(), theirDid);
let meta = JSON.stringify({
theirEndpointDid: theirEndpointDid,
verified: false // Indicates that the owner of the agent has confirmed they want to stay connected with this person.
});
//FIXME: Check to see if pairwise exists
await sdk.createPairwise(await indy.wallet.get(), theirDid, myDid, meta);
Can anybody help me out?
In your code, there's actually 2 places where IndySDK 1.11.1 can throw 212 WalletItemNotFound.
1. The first is on this line:
let theirVerkey = await sdk.keyForDid(await indy.pool.get(), await indy.wallet.get(), theirDid);
IndySDK will first try to see if the DID under variable theirDid is not one of your DIDs, stored in your wallet. If no, it will try to find this DID on the ledger. If it's still not found, it will throw WalletItemNotFound. You can check out this behaviour in the IndySDK Rust code here:
https://github.com/hyperledger/indy-sdk/blob/v1.11.1/libindy/src/commands/did.rs#L331
2. However I assume this is not actually your case and you having this error coming out from
wait sdk.createPairwise(await indy.wallet.get(), theirDid, myDid, meta);
If you look how is this method implemented in Rust
https://github.com/hyperledger/indy-sdk/blob/v1.11.1/libindy/src/commands/pairwise.rs#L84
you will see that it's calling get_indy_record for both theirDid and myDid you've supplied. Hence you can't create pairwise record without having both DIDs stored in wallet first. You can assure your wallet contains theirDid by calling storeTheirDid method. In
sdk.storeTheirDid(wh, {did:'V4SGRU86Z58d6TV7PBUe6f', verkey: 'GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL'} )
After calling this, you will be able to call createPairwise between you and them without an issue.
IndySDK version / caching note
I think you might be using some older version of IndySDK. In IndySDK 1.11.1 when keyForDid resolves something from ledger, it actually caches this data, so the code you've posted actually worked out of the box for me without an error.

UnhandledPromiseRejectionWarning when using Fluture `encaseP` on `fetch`

I have just started using Flutures, and I am trying to fetch some remote data for a visualization with d3.
I created a function which accepts a DOM selector (e.g. #my-chart) and a url (e.g. https://example.com/data.json).
If an error occurs when fetching the data, I have a unary function that shows an error message. If everything goes well, I have a unary function that draws the visualization. For the sake of simplicity, let's suppose that these functions are just console.error and console.log.
const fn = async (selector, url) => {
// convert fetch (which returns a Promise) into a function that
returns a Future
const fetchf = Future.encaseP(fetch);
fetchf(url)
.chain(res => Future.tryP(_ => res.json()))
.fork(console.error, console.log);
}
Apparently I am missing something when wrapping fetch in a Future, because I get this warning:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
If I had to use async/await I would write something like this, which would not give me any warning.
const fn = async (selector, url) => {
let res;
try {
res = await fetch(url);
} catch (err) {
console.error(err);
return;
}
let data;
try {
data = res.json();
} catch (err) {
console.error(err);
return;
}
console.log(data);
};
It seems two things are going on here:
The data.json() function is not supposed to be wrapped inside tryP, because according to your second not broken example, it returns synchronously (there is no await). This would cause Fluture to raise a TypeError (because it expects to see a Promise, but gets a JSON value). Although, knowing the fetch API, data.json() typically does return a Promise, so it might also be your second example is broken, and something else is going on. Whatever it is, I suspect that an unexpected Error is being thrown somewhere. Do you see any other error messages in your console, besides the one you posted?
I did some testing, and it does seems to be true - when Fluture raises or catches a TypeError after a successful encaseP, it seems the original Promise manages to catch that error, and trigger the unhandled rejection. This appears to be a regression bug in Fluture, and I will be fixing it soon. In the meantime, if we get to the bottom of what's throwing your error, you will be able to continue without depending on said fix.
EDIT: I've opened a PR to fix the second issue: https://github.com/fluture-js/Fluture/pull/310
EDIT2: The fix has been released under version 10.3.1. Using that version should give you more insights in what's happening with issue 1.

How to allow Flutter to get a value that it stored in a firebase server or any server?

Right now I am using an http 0.11.3+16 and I am able to add a true value to an item on the site using the following function:
if (newAcceptStatus) {
response = await http.put('https://example.com/example1/${selectedOrder.id}/example2/${_authenticatedUser.id}.json?auth=${_authenticatedUser.token}',
body: json.encode(true));
this function is only called when the admin is logged in and the admin is the only one that can change the status of the Boolean, so the value is stored under the admins id and token. so I tried the following to help show if the item was changed by the admin to the user but i keep getting that the value is null when i decode the response with the following function:
Future<Null> checkAccept() async{
http.Response response;
response = await http.get('https://example.com/example1/${selectedOrder.id}/example2/(admin id goes here).json?auth=${_authenticatedUser.token}');
accepted = json.decode(response.body);
}
not sure what i am doing wrong. any help would be appreciated!
I was calling the wrong list of items which were very similar, thus giving me an empty list

Get HTTP Status using swift

I am sorry, I haven't found an answer for my question(( Please, don't be very harsh, I am not a professional programmer, but I keep learning and hope once I will be able to answer someone's question))
I am trying to get HTTP Status of the link (I am sort of generating links depending on one database entries code, like ABCDEF, I keep them in an array and then generate a link to second database, like www.blablabla.ABCDEF.net), so I can see whether the page exists in database or not.
I have written this code, but something is wrong. So maybe it's a question like: "What's wrong with my code?" But on the stack they also say, you have to show your attempts of problem solving...
I wish I could keep it all swift, without any additional modules or something, I think NSHTTPURLResponse must be enough, but I am using it somehow wrong.
Looking forward to help and replies))
var err: NSError!
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData!, error: err) -> Void in
if (err != nil) {
let httpStatus: NSHTTPURLResponse = response as NSHHTPURLResponse
for myLink in allLinks {
println("HERE IS THE CURRENT STATUS CODE" + httpStatus.statusCode + "OF A LINK:" + myLink)
if httpStatus.statusCode == 200 {println("SUCCESS!!!!!")}
}
}
}
The fundamental issue here is that you appear to be looking at the statusCode only if the err is not nil. But if you have error, you probably don't have status code. The error parameter to the closure indicates fundamental network issue that probably prevented you from getting to the page in question. The statusCode is generally only meaningful if the error was nil (i.e. you succeeded in connecting to the server), in which case the statusCode is how the server informs you of its ability to service the HTTP request.
A couple of minor things:
You don't need the var err: NSError! line (because the error object is passed as parameter to the closure). This variable you've declared is not used here.
I don't see how error: err as the third parameter to the closure could have worked. The syntax is "variableName: variableType", but there is no type of err.
Likewise, your code is referring to a non-existent class, NSHHTPURLResponse. In Swift 3 and later, it's HTTPURLResponse.
It's probably prudent to do if let for the retrieval of the HTTPURLResponse in order to get the statusCode.
I'm unclear as to your intent in iterating through allLinks, because this connection is just for a given request, not a bunch of links. Just look at the statusCode in light of the particular request. If you need to test multiple URLs, then you do a separate request for each.
We should consider any codes between 200 and 299 as success, not just 200. I'd suggest using the range 200 ..< 300.
Thus:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
print("No valid response")
return
}
guard 200 ..< 300 ~= httpResponse.statusCode else {
print("Status code was \(httpResponse.statusCode), but expected 2xx")
return
}
// everything OK, process `data` here
}
task.resume()
I also made a few other changes (updated for Swift 3 and later; use URLSession rather than URLConnection; I think error is fine choice for the variable name; I prefer the trailing closure syntax; I tend to use inferred types for closure parameters to make the declaration a little more concise, etc.), but all of that is immaterial to the question at hand: Hopefully this illustrates how one checks the status code.
For Swift 2 rendition, see previous revision of this answer.
[Swift 5.2]
Hi there, you can try this one:
let task = URLSession.shared.dataTask(with: yourRequest) {
(data, response, error) in
guard let response = response else {
print("Cannot found the response")
return
}
let myResponse = response as! HTTPURLResponse
print("Status Code:", myResponse.statusCode)
}
task.resume()
Here is the output
Status Code: 200
(This is your StatusCode)

Resources