I don't know pyramid or pylons, but everyone I know who works with web frameworks these days won't shut up about FastAPI as the new darling, especially its built-in support for async functionality.
You would want to call the API as few times as possible. FastAPI has built in streaming support.
https://fastapi.tiangolo.com/advanced/custom-response/?h=stream#streamingresponse
​
It really should be as simple as using the streaming response. The hard part is making the API/UI robust to network dropouts, missing packets, and anything else that could happen during a 1+ hour video stream. Breaking the video into chunks, using a python lib that can seek in the video, using compression, keeping play state of a video for the user in a DB so you can resume at any point.
All of that makes video streaming hard.
Well in most of my Django projects, I go with DRF, no second thoughts, UNLESS the API has to be async, then I go run to fastapi, it's pretty great. Now to your question, I will chose Angular over React any day, I worked with react for over a year and I hated every moment of it. Angular fits so beautifully with Django right out of the box it's ridiculous to me. You don't have to stray away from your Django basics, you create models, then you create services to interact with those models and you create components to call those services and perform actions. It's very organized, I wouldn't wanna work with react in the near future. But I would encourage you to use React, try it for yourself, you'll either love it or start loving angular even more.
> I thought ApiStar would be it, but then it was abandoned by its creator.
FastAPI creator says he was inspired by APIStar before it became a set of tools to validate OpenAPI specifications instead of a web-framework.
FastAPI is based on Starlette. APIStar and Starlette are created by the same author - Tom Christie.
So, it may work for you. :)
​
I have no experience in using these technologies in large teams though.
def create_student(student: schemas.StudentCreate
The typehint here controls the validation. Assuming StudentCreate is a Pydantic model with a `gpa` field defined, then any requests missing that field will return an appropriate error auto-magically.
Python has become fast enough for most purposes these days. If you're looking for speed, don't go for flask. Go for FastAPI. It has the same UVLoop as Node.js, yet is much easier to handle if you ask me. They also have background tasks built in.
​
It's not uncommon to have a lot of text and documentation in your code. In fact, it's considered good practice, as that's where it belongs - next to your code.
Personally, I try to keep text in the Field.description
short with longer, more descriptive text in docstrings.
Forget that comment, you still want to have local env to test things out, you can think about dockerizing the app later. There is a great section about that in the docs.
You can also try FastApi: https://fastapi.tiangolo.com.
It have also some type hints from Python 3.6 what I know..
Or Kotlin with Ktor or Spring framework is also possible.
Yeah, you could achieve many of the same things with a reverse proxy, at the cost of significant complication. With ASGI its usually very simple.
Say I've written a REST api using e.g. FastAPI and want to add GraphQL support with e.g. Strawberry. Without ASGI, I'd gave to run two seperate server processes, plus nginx/caddy/whatever, deal with the routing rules in multiple places, etc.
Thanks to ASGI, its literally one line: fastapi_app.mount("/graphql", strawberry_app)
And that's probably the best case for a reverse proxy as a substitute for ASGI.
I can also take advantage of any backing services which I've already written code to use without having to duplicate said code across two programs, flexibly decide which how to dispatch to different sub-apps based on information which might be hard or impossible to get at with a reverse proxy setup, etc.
It also enables easily changing part of the server's stack. Typically in python you'll use one module to write your server (e.g. fastapi) then another to actually serve it (e.g. uvicorn). If you decide to change either of those out, you can, without effecting the other.
Those were just a few example I came up with off the top of my head late at night. There's probably a fair bit I'm not thinking of at the moment.
I'm intrigued by this, currently I'm also creating a rest API (with fastapi rather than Django) so am learning all this myself.
FastAPI recommends bcrypt (https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/), is this an outdated recommendation then?
Hätte Bock hier mitzumachen. Meine Talente:
Arbeite mich aber auch gerne in neue Stacks ein. Vor allem Go oder auch Spring Boot würde mich interessieren.
If I had to choose, I would go with FastAPI.
However, always bear in mind that these are "just" our opinions.
There really shouldn't be "competition" between libraries and frameworks. They're all great tools and the choice really just depends on the specific needs you will have for each of your projects. The really ideal answer to your question is "you really should learn both" :)
I’m in the very slow process of migrating a giant Flask app to FastAPI. I want to make breaking changes as part of the change anyway, so I have the new API at a new URL. Instead of moving paths, I’m adding features to the new API one by one and cutting over consumers (e.g. UI components) as they’re ready.
If you want to take a more unified approach, rather than having a completely new API, perhaps this (https://fastapi.tiangolo.com/advanced/wsgi/) will help?
Hey @sandys1, FastAPI creator here :)
You don't really have to deal with async stuff. You can use standard SQLAlchemy as is, and use all the standard def
functions everywhere.
FastAPI is directly based on Starlette. You can think of it as Starlette on steroids. It adds simple but powerful tools for building APIs on top.
In FastAPI you declare your path parameters, bodies, headers, etc. using standard Python type hints.
And FastAPI does automatic validation, data conversion (e.g. getting an int
from a query parameter), and documentation (all using standards).
So, you get an automatic, interactive, API documentation site, for free.
The other way to do it (without FastAPI), would be to check each one of the requests you receive in your own code, to see if they have the correct shape, types, etc. FastAPI does all this for you, even for deeply nested JSON bodies, all based on standard Python type hints.
If you are not building an API (only rendering templates in backend), there's not a big advantage in FastAPI. Otherwise, there probably is.
Give it a try, it takes about 10 - 20 min. Only the example in the frontpage. That's enough to know if you like it or not ;) https://fastapi.tiangolo.com/
I think Dependency injection is more relevant than middleware in your case.
I have a project where a few systems endpoints can only be accessed by staff users on our Django site. So the endpoint looks like this. The celery_router
will use admin_auth_router
authentication.
app.include_router( celery_router.router , prefix = '/celery' , tags = ['Celery'] , dependencies = [ fastapi.Depends(admin_auth_router.require_user_login) ] )
But users do have access to reports & we use Google SSO. So any user would be able to access the endpoint. The reports_router
will use google_router
authentication.
app.include_router( reports_router.router , prefix = '/reports' , tags = ['Reports'] , dependencies = [ fastapi.Depends(google_router.require_user_login) ] )
I know that the use-case is not exactly the same, but it does seem pretty close.
I have used r/PySimpleGUI on several occasions and it is a great framework with which to create GUI front ends. It does take a little getting used to but the documentation is enormous. I get lost in its organization many times, but a little effort and you can find what you need.
That all said, there is also FastAPI for a Web framework if you want to go that route. As far as the executable goes, I have used PyInstaller for that with great success and it is super easy to use.
Good Luck.
I worked with both and find pydantic much nicer to work with. I do not see any reason, to use marshmallow in a new project. https://fastapi.tiangolo.com/ maybe shows, what you can do, besides their own documentation.
>Creating an Application/API
Cool cool, hope you're using https://fastapi.tiangolo.com/
>that pulls stats from the NHL API
God help you in your quest for accurate stats, then. You're going to run into lots of accuracy and testing problems. So much is randomly missing and even "lost" sometimes it is infuriating.
Django seems like overkill for your usecase. I'd go Flask between the two.
Also gonna mention FastAPI since it looks like your just gon a use it as the middleman between your data and front-end.
Python is a strongly typed by dynamically typed language and has been since it first appeared in the early 90s. Typing is still not enforced even in the latest 3.9.x versions.
There are advantages and disadvantages to this approach. It is highly convenient for rapid development, less so for performance.
Take a look at FastAPI for microservices, and, of course, look at deployment using docker/kubernetes.
I'm with you on the Depends injections. And implementing them as default values for function parameters is odd, to say the least.
But overall, it's a great piece of software so....
Also if you don't like having to repeat deps in function sigs, you can add deps to path decorators and/or router instance.
https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/
You might want to consider exploring FastAPI
as well as Flask so you an provide APIs on your new status site. https://fastapi.tiangolo.com/
The dash
library might also be of interest. https://plotly.com/dash/
Python fastapi to receive the api request. They have an image and example how to deploy with docker. The whole thing is reasonable short without much overhead.
https://fastapi.tiangolo.com/deployment/docker/
Build your text file and write it to disk. Then use os.system() to run the git commands.
Unlikely. Those views are already serving your GET and POST request with standard responses. To get those working with a REST API, you'd need to do some extra work to serialize contents into JSON responses, accept data from the POST requests as JSON, etc. Basically you'd be doing a lot of extra work to get the same view to respond in two very different ways to different requests, which can be a headache to maintain.
It's fairly simple to add a REST API to your existing application by implementing Django REST Framework (or one that's come along recently I have yet to try, django-ninja, which is inspired by FastAPI). Leave your templated views alone to keep working as they do, and simply add the REST functionality elsewhere in the app, which you can then serve under some api/
URL.
When you're building REST APIs and don't need a full-stack app (Django) or you want a bunch of niceties like type assertions without a million plugins (Flask).
Well, there are alternatives in that they either use a single endpoint or automate the creation of endpoints. GraphQl uses a single post endpoint, and odata is similar (though typically more than one endpoint is created) in that it would allow you to do more with less endpoints. A friend was showing me fastapi to autogenerate endpoints. I think the rest layer is getting automated more and more, similar to when people started switching from embedded sql statements and stored procedures to more orm usage.
In thoery, if you use some production grade webserver, you can router based on "host" and based on "url" requests, to specific scripts.
I'm not sure if whatever FastAPI intends to use as production server can handle it.
https://fastapi.tiangolo.com/deployment/manually/
Uvicorn? Hypercorn?
EDIT: looks like it can work with WSGI, which works with apache web server.
Paid but totally with it: https://testdriven.io/courses/real-time-app-with-django-channels-and-angular/. They have the same with React instead of Angular.
Also, if you want to ditch Django but keep Python, check FastApi, which is wonderful for APIs. I set up a working socket in a few minutes : https://fastapi.tiangolo.com/advanced/websockets
Start with the docs. It's a great place to not only learn FastAPI -- but design patterns, async/await, and software architecture in general as well!
Check out https://testdriven.io/blog/topics/fastapi/ for a few additional tutorials on-
I got momentarily distracted from coding by a framework different from the one I'm using and came across this really cute explanation of concurrency (edit: I kind of object to the explanation of parallelism, but that's neither here nor there)
Python has FastAPI now
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
Be careful not confuse message queues (brokers) with asynchronous features in languages!
When using a full-blown asynchronous message queue such as Celery + Redis, the asynchronous code is executed in parallel in a different process (which can be distributed on other machines, etc.).
When using the asynchronous feature of a language (Python Asyncio, Node.js, etc.), the asynchronous code is executed concurrently within the same process (it can be distributed among multiple threads if supported, but not for Node.js for instance) : this is just a "simple" event loop perfor
For OP, you can checkout FastAPI / Starlette for an example of lightweight background task using Python Asyncio facilities (https://fastapi.tiangolo.com/tutorial/background-tasks/).
TLDR: for lightweight/quick background tasks, you can make use of the asynchronous feature of a language (does not worker in serverless though). For long-running background tasks, use a full-blown message broker.
We love how it generates openapi/swagger specs from our code.
We also love the way it enforces the in/out arguments with pydantic
Switching from different approaches, fastapi is the one we're sticking with. It fits well from single lightweight app to full-blown microservice (k8S/knative/istio).
If it's just an API, I might look at FastAPI over Flask.
Nothing against Flask... I just see it as more of a full on MVC controller than a simple API server.
If I were doing a full-on web app with a front end, I'd use Flask. For just serving up API endpoints, I'd go with FastAPI.
Seems fine from what I see!
For project template structure you can this page: https://fastapi.tiangolo.com/project-generation/
GitHub link:
https://github.com/tiangolo/full-stack-fastapi-postgresql
But you can adapt as per the scale of your application
Not an expert on FastAPI or Uvicorn, but is there a reason you're rolling your own image and not using the official image? Even if you want to hand-roll everything yourself, it might be a good place to look for how the same job is achieved and give you insight on what yours is missing.
You can use any database with FastAPI. It's just a web framework. You don't have to use the same ORMs shown in the tutorials.
> FastAPI works with any database and any style of library to talk to the database.
> A common pattern is to use an "ORM": an "object-relational mapping" library.
Direct quote from the docs here: https://fastapi.tiangolo.com/tutorial/sql-databases/
FastAPI's documentation has a [section](https://fastapi.tiangolo.com/tutorial/security/) about setting up authentication for the API. I'd like to say though that authentication is no joke, it's the most difficult part of the system and from experience I can say most people get it wrong. If this is for internal use, you can consider putting the website in a private network only accessible through a VPN, and then maybe you don't need login at all?
Do you use Active Directory or something similar for internal logins in your company? If you do, you can build an integration with that to handle the logins. In that case, you'd only need to worry about validating JWT tokens. Again, not something necessarily easy to do (and AD in particular has significant gotchas). For token validation I've done a tutorial myself.
The final question is do you really need FastAPI for this? For an internal admin site, like u/Cognizantauto95 says you'd be very well served with Django and its built-in admin site, with login included, database integration, and much more. You can also deploy the Django admin to a private network for security.
A PUT operation is meant completely replace an item, the request meant for partial updates is the PATCH.
The FastApi docs explain how you can implement a PATCH operation:
I think it does. It's pretty straight forward if you are familiar with jinja.
I loved FastAPI in Python. Excellent documentation. It even goes into details of things that are typically assumed to be known (e.g. Python types, concurrency, etc.). It also provides helpful links to understand the basics of web frameworks.
Looking at the documentation https://fastapi.tiangolo.com/tutorial/request-files/, the UploadFile object is already open, so you should be able to use it directly: object_id = calculate_md5(file)
, modifying the calculate_md5
function to
def calculate_md5(filename): file_hash = hashlib.md5() while chunk := f.read(8192): file_hash.update(chunk) return file_hash.hexdigest()
That's not true. The docs do a pretty good job at pointing you in the right direction https://fastapi.tiangolo.com/tutorial/bigger-applications/.
It's basically like Flask blueprints. You define decoupled routers in multiple files and then you use app.include_router()
. You can't dismiss FastAPI as disingenuous when you overlooked everything beyond the getting started.
If you know typescript you could build something around typescript backend tooling. I just recently created a post How good is typescript as a backend language? on reddit and many people said that typescript is super awesome but there is not as much tooling for backend development as in other languages like java & kotlin for example.
Maybe you can make something like fastApi in typescript. fastApi grew super fast and is considered not the state-of-the-art REST backend for python. I don't know how the creator earns money but I guess with donations you could reach 2k$ per month quite comfortably.
Map each one(Auth etc) to the corresponding http status code in the response
kwarg here: https://fastapi.tiangolo.com/advanced/additional-responses/#additional-response-with-model
Also make sure to type hint all your models extending BaseModel so that the documentation can be generated and everything serialized properly at runtime.
To add on to this, I don't think that Django is the only reasonable option anymore. FastAPI has been gaining a lot of popularity in the last couple years and is a lot easier to get started with.
Your route isn't async. Flask can do async routes since v2.0.
The event loop is used to perform async tasks. I haven't done any async Flask. I typically use FastAPI for writing APIs. It's just so good and easy to use.
elaborating on the last comment: you're going to want to copy all the python code from your jupyter notebook into a .py file, and then use a web server like fastapi (there are many more options too; you might also want to try Flask, Django, or others). Then your web app can make an http request to the server endpoint that you just made see here.
I haven't tried it yet, but this use case is described succintly in the FastAPI docs
FastAPI supports async out of the box, and encode/databases provides async support for querying the database.
Then the endpoint will run in a threadpool itself.
Does the endpoint need to wait for all the threads to terminate or would it be okay to return early?
If it doesn’t need to wait for them, it’s probably best to use background tasks or celery for this.
I guess in the one application, the one that is showing the images, you can expose an API endpoint that the other script can call, and it will show what is the "Active Image". You can use FastAPI and get something running in a couple of lines of code.
There is a prepackaged docker image using uvicorn/gunicorn from the same guy who made fastapi. Read me should be enough for you to get going.
https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker
Also be worth reading offical docs on doing this yourself too. https://fastapi.tiangolo.com/uk/deployment/docker/
Well you'll need to make the db connection async as well, using an async db library. The FastAPI docs mention encode/databases, which is a wrapper over SQLAlchemy; if you don't need the ORM then go straight to the underlying db driver which is aiomysql.
OP, dando uma lida rápida no seu código, me parece que vc quer fazer uma API que realiza operações CRUD (create, read, update e delete).
Eu recomendo a FastAPI. Django e Flask são bons, mas fazem muito mais do que você precisa e são, portanto, mais complicados.
Mas o que suspeito que será sua principal complicação é que você não está usando nenhum banco de dados. Sua aplicação como funciona hoje só manterá os dados durante sua execução, pois estão todos armazenados em variáveis.
Aqui tem um tutorial que pode te ajudar.
Have you heard of FastAPI? Pure Python. They say it competes with Go and node.js APIs in performance, and it's SOO easy to code.
I think Microsoft is using it a lot for their machine learning APIs.
If you set up the connection to the database as a dependency, then you can override that dependency in the tests to return whatever you want.
https://fastapi.tiangolo.com/advanced/testing-database/
In this example, he sets the override to use a testing database, but if you can set it to just return a class or a mock object.
def get_conn(): return MongoUser
async def find_user(email: str = Query(None), mu=Depends(get_conn)) check_user_exists = mu.objects(email=email) . . .
In your testing file
class MockedClass(): def objects(email: str =None): return "" //Or whatever it should return
def override_get_user(): return MockedUserClass()
app.app.dependency_overrides[get_conn] = override_get_user
Python Fast.API would be my go to for most API purposes: https://fastapi.tiangolo.com/. It allows you to directly return dictionaries and automatically handles proper response types as well as auto-generating basic docs for all of your routes. It’s also extensible enough where you can add in good response validation, which is typically much harder in other micro-frameworks like Flask. If you want to stay on the javascript/node.js side of things, I would take a look at Express.js, which can also be good in many circumstances and is pretty lightweight. I’ve never used nestjs, but Django at least is pretty heavy and more geared towards CMS usage and personally even for that I would stay away from it.
If you have a long running process, you can use celery to handle that unit of work in another thread letting flask handle the web requests.
FastAPI has this async functionality out of the box and its syntax is similar to Flask. https://fastapi.tiangolo.com/tutorial/background-tasks/
You're running into exactly what I said you would run into with a recursive function. Don't do this. Also, there is zero need to make app
a protected variable.
I think you should revisit some tutorials on fastapi.
Don't return a python data structure in a web call. Return a standardized data structure, json
in this case, and remove the response_model
parameter from your decorator. You don't need it unless you're actually going to use a model in your response, which you are not.
The problem is that while you might make the function Depend
on the get_db
you don't actually ever do anything with the database.
Look at your code and take out a rubber ducky if you need to. Your function is named new_internship
and it takes two parameters, internship
and db
. In your try
block you just call yourself with the same parameters, but nothing is ever done with the database other than getting a connection. This is equivalent to putting a car on a round racetrack and watching it go round and round and accomplish nothing because you've created a recursive operation.
@internships_router.post("/new-internship", response_model=dict) async def new_internship( internship: InternshipSchema, db: Session = Depends(get_db), ): try: # Internships_schema.validate(internship) await new_internship(internship=internship, db=db) return { "message": "created-internship", "internship": internship, "status_code": 200, } except Exception as err: return { "message": "Bad Data", "internship": f"Bad data. The Error is: {err} and the data you sent is {internship}", "status_code": 400, }
We use Sphinx for Black which I guess is still the gold standard documentation system, with especially mature support for Python projects. We did feel like ReST was a bit heavy in terms of markup though, so instead, we're using Markdown for most documentation files. This is possible thanks to the myst-parser library which contains a Sphinx extension.
It seems MkDocs is gaining traction, you can see it in action in FastAPI docs. I personally haven't used it yet so can't compare.
In any case, I feel we're pretty lucky in terms of the availability and maturity of documentation tools. The issue isn't lack of tooling but rather being thorough enough and knowing your audience.
https://fastapi.tiangolo.com/advanced/wsgi/?h=wsgi#using-wsgimiddleware
Yea python web frameworks all share wsgi and/or asgi as common interfaces for running a server. Django can use either wsgi/asgi and fastapi can mount either asgi/wsgi.
Yes although I'm unsure how worthwhile it is(speaking strictly from a performance perspective) to even create routes specifically to isolate synchronous-only def
code.
https://fastapi.tiangolo.com/async/#path-operation-functions > If you are used to defining trivial compute-only path operation functions with plain def for a tiny performance gain (about 100 nanoseconds), please note that in FastAPI the effect would be quite opposite. In these cases, it's better to use async def unless your path operation functions use code that performs blocking I/O.
Which I'm interpreting as: "There's ~15ms overhead for running synchronous code in a thread/process pool executor. If your code block/function/etc runs faster than ~15ms a def
path(or manually using loop.run_in_executor) and is cpu-bound, you shouldn't use a def
path since it will just add overhead.". ORM calls figure to be blocking I/O so this doesn't necessarily apply, but you get the idea.
I wouldn't worry about trying to optimize all this though until you really have to.
You should be able to use dependencies for reusable logic like this. See:
https://fastapi.tiangolo.com/tutorial/dependencies/
https://fastapi.tiangolo.com/advanced/advanced-dependencies/
Alternatively, Pydantic models give the ability to provide pre-item custom validator functions as part of classes.
https://pydantic-docs.helpmanual.io/usage/validators/#pre-and-per-item-validators
You need a server to communicate between your web page and your scripts. Your server will serve up your web page. It will also define your web API.
I skimmed the Flask beginner tutorial. It seems more complicated than it is. Ignore auth and cookies and database connections at first. Just get a simple home route printing to the terminal and sending a string back to your browser.
https://fastapi.tiangolo.com/tutorial/first-steps/ does it in about 5 lines. You can port that logic to Flask or any other framework.
From there figure out how to receive data at a route, probably using JSON. Maybe POST run-script/ Call your script using that data. Send a response with data from your script result. You can test this out with Postman, curl, httpie, or using JS fetch in your browser dev console.
Now have GET / serve up a bare bones web page. Get that talking to your end point, probably with JS sending JSON. Maybe just a button. On click you POST a payload to run-script/.
Let me know if you need help.
Hey All!
Brad from DevOps Journey here with another video showing off the popular Python modules.
In this video, I show off FastAPI and how easy it is to build your own REST API.
My video is meant to be a starting point. Documentation for FastAPI can be found here:
Thanks and please let me know what you think of the video!
Hey All!
Brad from DevOps Journey here with another video showing off the popular Python modules.
In this video, I show off FastAPI and how easy it is to build your own REST API.
My video is meant to be a starting point. Documentation for FastAPI can be found here:
Thanks and please let me know what you think of the video!
Hey All!
Brad from DevOps Journey here with another video showing off the popular Python modules.
In this video I show off FastAPI and how easy it is to build your own REST API.
My video is meant to be a starting point. Documentation for FastAPI can be found here:
Thanks and please let me know what you think of the video!
You can use Vue.js with a Python web framework like Flask if you wish.
https://blog.logrocket.com/flask-vue-tutorial-examples/
Alternatively, you might just want to use Python as a backend offering an API. Take a look at FastAPI for this. You would call the API from your javascript code.
Alternatively, you could look at doing the dashboard in Python rather than Vue.js using something like dash.
ASGI is a specification, not a library. Its a standard interface for python async webservers.
Basically, an ASGI server is an async callable which takes three things: a scope (which contains things like the HTTP method, url, headers, etc. in a well defined way), a async callable "receive" which is used to receive any content sent from the client (e.g. the body of a post request), and another async callable "send" which is used to send data back to the client.
The advantage of making your server compatible with ASGI is that it means virtually all the other python async web frameworks can be "plugged in" to it easily. For example, if someone wanted to add an existing webapp written with FastAPI or graphql support with e.g. Strawberry, they can do that easily, without you having to do anything. The lack (from what I've seen) of anything like ASGI (or its older sibling WSGI) is something I really miss in Rust as a python developer.
It's harsh cuz you come here promoting yourself and your product. You disguise it as a deployment guide. Which is not even a guide, but some low quality content. And it's not how deployment should work in any context.
All you did is a hello-world example from here https://fastapi.tiangolo.com/tutorial/first-steps/
Where you replaced return hello-world
with return pipeline.predict()
.
You deserve to be permabanned from posting on this sub, not some harsh words.
I ended up using sqlacodegen to generate the models code to reflect and used it like the tutorial
Thanks for showing me that tool!
Yep I really think that's a super nice feature too. You can run "very quick background tasks", like I wrote, just like sending emails, or very quick data processing. You can read how to do that in the docs. However, running a machine learning model isn't "very quick", so for long running (and computationally intensive) tasks the only way are other solutions, like Celery (it's not the only one of course).
It worked! I was able to snag a site at Bridge Bay campground in July. Very excited. Definitely wouldn't have been able to do this without your tool.
If you ever decide to put a UI in front of it (for config/settings), FastAPI is all the rage these days for a back-end.
>Is it possible to serve opyrator as part of a larger FastAPI project, e.g. at a particular URL? It looks like each function has to run in its own process, that's not very flexible or nice for developers.
This alpha version is focused on single operations (not a replacement for a full web API), but I think it should be quite straight forward for us to support something like sub-application mounting in fastapi (https://fastapi.tiangolo.com/advanced/sub-applications/?h=mount).
Take a look at using Python, Fast API and uvicorn, very simple to create web services. Python also has some really good libraries for creating/updating Excel files, openpyxl is a very popular library.
For just an API rather than a general webservice, I suggest you look at using very popular FastAPI framework.
Regarding authentication, here's a document on the topic for FastAPI:
I second this.
I personally fell in love with building APIs using Python+FastAPI for my backend and then putting a Vue application in front of it!
And yeah I've had to work on C# some times as well. Having at least a fundamental understanding of it can't hurt and I quite like the language in terms of syntax and concepts.
request: Request is supposed to reference a model, typically using Pydantic. Then the all lowercase request is what you'd use in your function.
https://fastapi.tiangolo.com/tutorial/response-model/
Here is a good introductory video that will walk you through it. https://www.youtube.com/watch?v=kCggyi_7pHg
Are you following the instructions from the documentation page? https://fastapi.tiangolo.com/tutorial/
To run the API you should use an ASGI server like uvicorn such as the documentation says
Yes. BaseModel is imported from pydantic to be used in creating new models used in FastAPI as shown in all the documentation examples. Thanks for clearing that up.
It can be a good practice to put the data behind an API layer - that way the schema of the underlying data schema can change as needed but you can ensure the interface to get at it remains compatible with any downstream applications that consume it.
In Python it's fairly straightforward to use Flask to do this, but may be better to use an API-specific framework such as Falcon or FastAPI, depending on how much firepower you need.
https://falcon.readthedocs.io/en/stable/ https://fastapi.tiangolo.com/
The OAUTH2 Scopes example in the docs uses username/password to generate a JWT, then uses the JWT to auth with scopes. The only part of the example that really uses "OAUTH" is
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends())
You should be able to replace the form_data...
with some other form of auth that works better for you. If the user already has a JWT (not sure how...) they can just use all the other routes in the OAUTH with Scopes example.
https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/
Use FastAPI instead of Flask. Will be faster and easier. Super easy to use on AppEngine too. Also, I'd recommend using orjson for the JSON parsing. It'll save you a lot of headaches with formatting and again be faster.
So you want to log all the requests to "/" in your api with timestamp and ip address, then you'd have to check FastAPI documentation on how to get the information from the request.
FastAPI can be spun up pretty quickly. You can also make endpoints with php very very easily.
You could also look into “serverless” architecture such as Lambda https://aws.amazon.com/lambda/
Don't think there is an API yet.
You can ssh to the device and setup your own API. A light API platform that you can use could be this. You would then have to write the backend code using simple exec statements with bash commands.
you don't NEED to use a different front end, if you just need a simple web page FastAPI can present static HTML pages and handle form data fine. I don't think this is the common use case though. as others have indicated using a JS based front end and interfacing with FastAPI via API's is the more common approach.
​
Information on processing form data can be found here: Form Data - FastAPI (tiangolo.com)
​
Presenting webpages w/ Jinja2 templates: Templates - FastAPI (tiangolo.com)
It’s good to stick with Postgres. And since you already know Python, you might be interested in this official FastAPI + Vue boilerplate: https://fastapi.tiangolo.com/project-generation/
We use it at work (Vue replaced by React, but you can stick with Vue) and it’s been really nice. It comes with auth baked in.
If you decide to go with this, I suggest you go through HTML, CSS, JS fundamentals, then Vue, and then start using the boilerplate project. Good luck!
A thing to note : Typer is made by the same guy who made FastAPI.
FastAPI uses the same structure as Typer, but for writing REST APIs, and it's great for that. It takes some getting used to, especially when used to a WSGI framework like Flask, since FastAPI is built on top of Starlette (which is an ASGI framework). Also, Starlette with a gunicorn runner is the fastest web framework in python.
FastAPI recently added a short deployment tutorial using Deta.sh
https://fastapi.tiangolo.com/deployment/deta/
It's free for the moment and easy to use.
Haven't tried it out, but this library seems promising: fastapi_permissions
Handling log ins can be done using fastapi itself: security
Sorry you got downvoted and no answers. This community wasn't very friendly to me either when I asked the same question last week. The only answer I got was one I left myself after I solved my own problem haha.
Basically you can't import from main.py in your routers because that would cause a circular dependency. There's already an import chain from your routers to main.py thanks to
app.include_router(<blah>)
The solution in the official docs is here: https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-dependency You'll have to tweak it a bit because the official docs seem to encourage giant monolithic files, rather than your simple project structure.
First, you have to move your common dependencies like db sessions to another file. I simply called mine database.py. Then you need to use FastAPI's Depends module to pass the shared resource to your routes. Looks something like this:
from database import get_db from sqlalchemy.orm import Session from fastapi import Depends .... @router.get("/items", response_model=List[schemas.items]) async def get_items(offset: int = 0, limit: int = 100, db: Session = Depends(get_db)): items = itemsDAO.get_items(db, offset=offset, limit=limit) return items
Your code to create the session goes straight in database.py. Then create a get_db function that returns the session. The source code from the docs worked perfectly for my get_db.
The comment above saying flask doesn't work with websockets made me think of fastapi. So have a look at fastapi
Think of it as an updated version of flask.
How about putting the databases stuffs in another file and import from it?
import databases
DATABASE_URL = f"postgresql://{user}:{password}@{host}/{db}" database = databases.Database(DATABASE_URL)
Also note the connect and disconnect so you don't have to connect in gps_get_test
: https://fastapi.tiangolo.com/advanced/async-sql-databases/#connect-and-disconnect
async will really only help you with IO bound operations like your loading of the image. The blurring of the image is the expensive part, CPU wise. You can move the blurring to use FastAPI’s loop.run_in_executor to get better response times. More details here - https://fastapi.tiangolo.com/async/