FastAPI graphql subscriptions - fastapi

I try to implement simple graphql subscription on FastAPI.
According to documentations but it is not working
import asyncio
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
from graphql.execution.executors.asyncio import AsyncioExecutor
from starlette.websockets import WebSocket
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
async def resolve_hello(self,info,name):
return "Hello " + name
class Subscription(graphene.ObjectType):
count = graphene.Int(upto=graphene.Int())
async def subscribe_count(root, info, upto=3):
for i in range(upto):
yield i
await asyncio.sleep(1)
app = FastAPI()
schema = graphene.Schema(query=Query, subscription=Subscription)
app.add_route("/", GraphQLApp(schema=schema, executor_class=AsyncioExecutor))
I googled and found that i might need to implement subscription-server like for Sanic or Aiohttp
I try but it doesn't work yet
from graphql_ws.websockets_lib import WsLibSubscriptionServer
subscription_server = WsLibSubscriptionServer(schema)
#app.websocket("/subscriptions")
async def subscriptions(websocket: WebSocket):
await subscription_server.handle(websocket)
return websocket
Error recieve:
return self.ws.open is False
AttributeError: 'WebSocket' object has no attribute 'open'
What i'm doing wrong and how it could be solved? Thank you.

I figured it out
below is workable solution
import asyncio
import graphene
import pydantic
from fastapi import FastAPI
from starlette_graphene3 import GraphQLApp, make_playground_handler
from graphene_pydantic import PydanticObjectType
class Subscription(graphene.ObjectType):
count = graphene.String()
async def subscribe_count(root, info):
for i in range(300):
yield f"{i}"
await asyncio.sleep(1)
schema = graphene.Schema(query=Query, subscription=Subscription)
app.mount("/", GraphQLApp(schema, on_get=make_playground_handler()))

Related

Details not found in FastAPI

I have orientation corrector class in seperate python file which takes rotated image and logo based on logo location it rotates image to correct orientation.
Now I am calling this class in fastapi but I am getting de
from orientation_corrector import OrientationCorrector
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile
import uvicorn
app = FastAPI()
app.post('/image')
async def orientation_corrector_image(file1: UploadFile = File("assets\rotated_marks.png"),
file2: UploadFile = File("src\configs\Logo.json")):
image = (await file1.read())
logo = (await file2.read())
print(image)
print(logo)
result=OrientationCorrector(image,logo)
return result
if __name__ == "__main__":
uvicorn.run(app, debug=True)```
from orientation_corrector import OrientationCorrector
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile
import uvicorn
app = FastAPI()
app.post('/image')
async def orientation_corrector_image(file1: UploadFile = File("assets\rotated_marks.png"),
file2: UploadFile = File("src\configs\Logo.json")):
result = await OrientationCorrector(file1.read(), file2.read())
return result
if __name__ == "__main__":
uvicorn.run(app, debug=True)

Cannot call reactReduxFirebase() - TypeError: Object is not a function

I an using redux-thunk as a middleware and trying to connect to redux-firestore. When I run the application I am getting the error "TypeError: Object(...) is not a function" at createStore.
import reportWebVitals from './reportWebVitals';
import {createStore,applyMiddleware,compose} from 'redux';
import rootReducer from './store/reducers/rootReducer';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk'
import {reduxFirestore, getFirestore} from 'redux-firestore'
import {reactReduxFirebase, getFirebase} from 'react-redux-firebase'
import FBConfig from './Config/FBConfig'
const store = createStore(rootReducer,
compose(applyMiddleware(thunk.withExtraArgument({getFirestore,getFirebase})),
reduxFirestore(FBConfig),
reactReduxFirebase(FBConfig)
)
);
I am using the extra arguments in my thunk actions like this:
export const createProject=(project)=>{
return(dispatch,getState,{getFirebase,getFirestore})=>{
//asyn call to database
const firestore=getFirestore();
firestore.collection('projects').add({
...project,
authorFirstName:'Nam',
authorLastName:'Pam',
authorId:123,
createAt: new Date()
}).then(()=>{
dispatch({type:'CREATE_PROJECT',project});
}).catch((err)=>{
dispatch({type:'CREATE_PROJECT_ERROR',err})
})
}
};
The error that you are seeing is likely due to upgrading react-redux-firebase from v2 to v3 (or basing new code on outdated examples). This update introduced some breaking changes such as the removal of the reactReduxFirebase store enhancer function. The package now uses React contexts and introduced some new hooks such as useFirebase and useFirestore which allow you to access firebase through the context in function components. But that doesn't help with your thunk.
In the page on Redux Thunk Integration, they recommend passing the getFirebase function to the withExtraArgument.
thunk.withExtraArgument(getFirebase)
As far as accessing firestore, this GitHub discussion recommends accessing it through the getFirebase function.
getFirebase().firestore()
You want your extra argument to be an object with properties getFirebase and getFirestore. We use getFirebase as one property and create an inline arrow function for the getFirestore property.
import {createStore,applyMiddleware, AnyAction} from 'redux';
import thunk from 'redux-thunk';
import {getFirebase} from 'react-redux-firebase';
const store = createStore(
rootReducer,
applyMiddleware(
thunk.withExtraArgument({
getFirebase,
getFirestore: () => getFirebase().firestore(),
})
)
);

No Firebase App '[Default]' Has Been Created Call Initialize

I am trying to upgrade to RNFirebase 6 from 5 and am going to move all my authentications from firebase.js sdk to RNFirebase and I am not sure why this initialization isn't working. I am using service everywhere so no idea what to be doing differently.
import { firebaseConfig } from '../configs/firebase';
import firebase from '#react-native-firebase/app';
import '#react-native-firebase/auth';
import "#react-native-firebase/database"
import "#react-native-firebase/dynamic-links"
import "#react-native-firebase/firestore"
import "#react-native-firebase/functions"
import "#react-native-firebase/iid"
import "#react-native-firebase/in-app-messaging"
import "#react-native-firebase/messaging"
import "#react-native-firebase/remote-config"
import "#react-native-firebase/storage"
import "#react-native-firebase/database"
import "#react-native-firebase/dynamic-links"
import "#react-native-firebase/firestore"
import "#react-native-firebase/functions"
let instance = null;
class FirebaseService {
constructor() {
if (!instance) {
this.app = firebase.initializeApp(firebaseConfig)
firebase.database().setLoggingEnabled(true);
instance = this;
}
return instance;
}
}
const firebaseService = new FirebaseService().app;
export default firebaseService;
So I didn't realize with React-Native-Firebase none of this initialization is needed. I am not sure why the initializeApp is in the docs or used anywhere. Hopefully this helps someone else out in the future since I banged my head against the wall all day

Redux createStore error: Expected the reducer to be a function

I'm getting an error on createStore and I'm not understanding why.
import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import thunk from "redux-thunk"
import promise from "redux-promise-middleware"
import * as reducers from './reducers';
const middleware = applyMiddleware(promise(), thunk);
export default createStore(reducers, middleware);
Above is my code and I get the error in the line
const middleware = applyMiddleware(promise(), thunk);
The error is Expected the Reducer to be a function.
I'm using React Native 0.37 and the latest version of redux, redux-thunk and redux-promise-middleware.
The reducers is the result of combineReducers.
Thanks in advance.
import * as reducers from './reducers';
There's no way that reducers is a function. You're going to get an object with each export as a property. You probably want:
import reducers from './reducers';

Getting: "TypeError: this.get$BrowserClient is not a function"

I'm coding a modified version of the AngularDart tutorial. I'm adding a server call based on the example in the Developer Guide/HTTP Client. Instead of the memory service, I'm trying to connect to an actual server on the same machine. I've gotten it to work in plain Dart using HTTPRequest in my Rails application. In my new AngularDart standalone client, I get the error:
TypeError: this.get$BrowserClient is not a function
I suspect this may be happening because I never created the in memory server in main.dart. If so, what is the correct code to talk to a real server?
My service class:
import 'dart:async';
import 'dart:convert';
import 'package:angular2/core.dart';
import 'artist.dart';
import 'package:http/browser_client.dart';
import 'package:http/http.dart';
#Injectable()
class ArtistService {
static const _artistsUrl = 'http://jazzcatold.loc/artists?page=1'; // URL to RAILS server
final BrowserClient _http;
ArtistService(this._http);
Future<List<Artist>> getArtists() async {
try {
final response = await _http.get(_artistsUrl,
headers: {'Accept': 'application/json'});
final artists = _extractData(response)
.map((value) => new Artist.fromJson(value))
.toList();
return artists;
} catch (e) {
throw _handleError(e);
}
}
...
My main.dart is:
import 'package:angular2/platform/browser.dart';
import 'package:jazzcat/app_component.dart';
main() {
bootstrap(AppComponent);
}
The example has:
import 'package:angular2/core.dart';
import 'package:angular2/platform/browser.dart';
import 'package:http/browser_client.dart';
import 'package:server_communication/app_component.dart';
import "package:server_communication/hero_data.dart";
void main() {
bootstrap(AppComponent, const [
// in-memory web api provider
const Provider(BrowserClient,
useFactory: HttpClientBackendServiceFactory, deps: const [])
// TODO: drop `deps` once fix lands for
// https://github.com/angular/angular/issues/5266
]);
}
Plan B
I tried this from the link given:
import 'package:http/http.dart' as http;
#Injectable()
class ArtistService {
static const _artistsUrl = 'http://jazzcatold.loc/artists?page=1'; // URL to RAILS server
Future<List<Artist>> getArtists() async {
final response = await http.get(_artistsUrl, headers: {'Accept': 'application/json'});
final artists = _extractData(response)
.map((value) => new Artist.fromJson(value))
.toList();
return artists;
}
I got the error:
EXCEPTION: Unsupported operation: IOClient isn't supported on this platform.
Plan C
I modified working code from another project:
import 'dart:html';
#Injectable()
class ArtistService {
static const _artistsUrl = 'http://jazzcatold.loc/artists?page=1'; // URL to RAILS server
Map headers = {'Accept': 'application/json'};
Future<List<Artist>> getArtists() async {
final response = await HttpRequest.request(_artistsUrl, requestHeaders: headers);
final artists = _extractData(response)
.map((value) => new Artist.fromJson(value))
.toList();
return artists;
}
When I check the network data on the Chrome inspector, I see the JSON data being returned. I'm getting the error:
html_dart2js.dart:3352 EXCEPTION: NoSuchMethodError: method not found: 'get$body' (J.getInterceptor$x(...).get$body is not a function)
The code may not be a fit for the getArtists structure.
You can't import http/browser_client.dart in a standalone application. That's only supposed to be used for browser applications.
See https://pub.dartlang.org/packages/http for examples how to use it for standalone applications.
The answer is a working version of Plan C above.
import 'dart:async';
import 'dart:convert';
import 'package:angular2/core.dart';
import 'artist.dart';
import 'dart:html';
#Injectable()
class ArtistService {
static const url = 'http://jazzcatold.loc/artists?page=1'; // URL to RAILS server
Map headers = {'Accept': 'application/json'};
Future<List<Artist>> getArtists() async {
HttpRequest response = await HttpRequest.request(url, requestHeaders: headers);
List data = JSON.decode(response.responseText);
final artists = data
.map((value) => new Artist.fromJson(value))
.toList();
return artists;
}
I rolled up the _extractData method into this one. I also coded it more precisely based on Günter's advice elsewhere. The getBody error above was in the extractData method that is not shown.

Resources