I am developing this project of a simple meme posting website where I take the UserName, caption, Image URL from the user and want to show all the memes on the home page of the website.
I am new to being a full stack developer, I am using FastAPI as backend and went through its documentation. So far I have been able to get the response from the HTML to the server via a Post request, but now I want to store the data in some database and send that data back to the Home page of the website. I tried finding tutorial videos but wasn't able to get the ones which could help me.
Any kind of help is appreciated.
Below is some code about how I am performing the current requests.
from fastapi import Request, status, BackgroundTasks
from fastapi.responses import JSONResponse
from tutorial import app,templates
import time
from datetime import datetime
from pydantic import BaseModel
from typing import Optional
class Record(BaseModel):
name:str
caption:str
meme_type: Optional[str] = None
img_meme:str
#app.post("/")
async def create_record(record: Record):
background_tasks.add_task(_run_task,record)
return record
def _run_task(name: str,caption: str,meme_type:str,img_meme: str):
time.sleep(3)
with open("memes.txt",mode="a") as file:
now=datetime.now()
content=f""" "Name":{name} \nCaption:{caption} \nURL:{img_meme} : now}\n"""
file.write(content)
FastAPI documentation has all the answers you need.
I want to store the data in some database
SQL Databases - You can use any relational database you want. The documentation has example codes using SQLAlchemy.
Async SQL Databases - You can connect to your relational databases using async/await using a third-party package called databases.
NoSQL Databases - FastAPI can also be integrated with any NoSQL. The documentation has example codes using Couchbase.
send that data back to the Home page of the website
HTMLResponse - If your app is simple and straightforward.
Templates - If you need template rendering. The documentation has example codes for Jinja2.
Related
As mentioned in the title, I attempt to
POST JSON file from C# (which is a WinForms accepting user input, then converted into a json), then to be received by python. I am quite clueless as to how to start at the C# side of the coding as I am still new to this. Would appreciate any kind help from here. Thanks
I use httpclient to communicate between the two languages, and now I would like to send the json file to the python side.
In short, the working principle of my project is:
User input parameters at WinForms that I have designed using C#, then these parameters are transferred over to Python by the flask and HTTPclient architecture.
Python process the parameters and a result is obtained, where I now wish to transfer this result back to C#, to be displayed on WinForms.
Flask is easy to use and set up for a simple POST request like this. The flask docs are excellent: https://flask.palletsprojects.com/en/2.0.x/quickstart/#a-minimal-application
Assuming you have pip installed Flask >= v2.0, a simple flask application to receive a POST request would look like:
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.post('/submit_input')
def submit_input():
# check that your data is json
if request.json:
data = request.json
# do something with the data here and create a new var...
new_var = 'this is some new data'
return jsonify(message=new_var)
I am new to Django and API creation. I am trying to figure out if it is better to use djangorestframework or just use JsonResponse. I got the suggestion of djangorestframework from Digital Ocean's tutorial but also found out about JsonResponse, which seems simpler given that I don't have to install another package.
Goal: I would like to be able to provide user information for both web and mobile applications.
I see that there are some reasons provided on this post for djangorestframework, which I pasted below for posteriority.
The common cases for using DRF are:
1)You're creating a public-facing external API for third-party
developers to access the data in your site, and you want to output
JSON they can use in their apps rather than HTML.
2)You're doing mobile development and you want your mobile app to make
GET/PUT/POST requests to a Django backend, and then have your backend
output data (usually as JSON) to the mobile app. Since you don't want
to pass back HTML to the mobile app, you use DRF to effectively create
a REST API that your mobile app can call.
3)You're creating a web app, but you don't want to use the Django
templating language. Instead you want to use the Django ORM but output
everything as JSON and have your frontend created by a JavaScript MVC
framework such as React, Backbone, AngularJS, etc. In those cases, you
can use DRF to output JSON that the JavaScript framework can process.
DRF basically provides you many features to make APIs that you don't have in raw django.
for example:
Serializers: a declarative way(django style like declaring models) of making serializers, when you use JsonResponse you have to tell everywhere what to serialize, with the serializer you have to import it and just use it, also this serializers can be able to save/update objects too. Also support ORM source to connect yours models(think how difficult would be serialize a model with nested relations with JsonResponse).
The Web browsable API, you can see all the availables endpoints.
Third party packages to install and use: https://www.django-rest-framework.org/community/third-party-packages/#existing-third-party-packages.
I am working on an angular 6 project and I need to know if I can get a database from a public api but also from an in-memory database?
Which means for example show movies from a public api but also be able to add my own movies so that it shoes on my website.
I just want to create a basic database that when I reload the page, the database disappears.
If yes, how can i do so without using backend?
Thanks
Ava
I really don't know if I understood your question properly but I thought of sharing some info which might be useful for you.
You can use the browser's local storage to temporarily save your data. And if you want your database to disappear when you reload, you can manipulate with logic to clear your local storage from the code. Like, onInit of the component, clear local storage.
Use json-server if you want a small data base. It actually serves as a real database
There are some public api sites, where you can fetch data, and even mock post and put requests too. For instance json placeholder
To be able to extend that data, you need the specific implementation to always extend the result with your "in-memory database". So for instance in a component, you store your data in a property, and in the http communication listeners do something like this:
this.http.get('placeholder-api',{someBodyData}).subscribe(
response => {
results = [...response, ...myInMemoryDbArray]
}
);
If you post the specific function you want to implement and has difficulties with, can help you more.
I think you can use firebase. For tutorial https://www.tutorialspoint.com/firebase/ .
I have a API defined in my project which returns JSON data in response.
url(r'^api/report/(?P<report_id>\w+)/generate/', staff_member_required(api_views.GenerateReport.as_view()), name="generate_report"),
In another app of same project, I want to receive this data in views.py
How do I make a request to this url using some django functions.
I think there might be some way to make this GET request without using requests or any other 3rd party module.
Any help would be appreciated.
I am currently trying to migrate a project from flask over to Django as practice and just to get it working on Django... I was wondering if there is a method within Django that performs the job of flask.jsonify?
If not, how else would you recommend I can emulate the same functionality?
from django.http import JsonResponse
def someView(request):
...
return JsonResponse(someDictionary)