how to download file from flask in react native - javascript

I am making a small app that downloads videos from youtube. I am using react native for the frontend, and python flask for the backend.
Here is the code on the server that downloads the video to the server and returns it to the client as an attachment
from flask import Flask, send_file
import vid_request
app = Flask(__name__)
#app.route("/<url>")
def download(url):
path = vid_request.download(url, r"\tempDownloads")
return send_file(path, as_attachment=True)
if __name__ == "__main__":
app.run(host="0.0.0.0")
// vid_request file
import pytube
def download(url, path):
url = "https://www.youtube.com/watch?v="+url
youtubeObject = pytube.YouTube(url).streams.filter(only_audio=True).first()
out_file = youtubeObject.download(output_path=path)
return out_file
This works when I go to the url and enter the youtube link, but when I do it from react native using this
await fetch(`http://192.168.0.12:5000/${input}`);
It doesn't work and gives an error, is there a better way for sending the file on the server side, or better way of downloading from the client side?

npx expo install expo-file-system
If its bare React Native, you need to additionally follow this steps:
https://github.com/expo/expo/tree/sdk-47/packages/expo-file-system
Amend the following
import { downloadAsync, documentDirectory} from 'expo-file-system';
import { Button, View } from 'react-native';
export default function App() {
const download = async () => {
console.log("downloading");
const { uri: localUri } = await downloadAsync('http://192.168.0.12:5000/video.mp4', documentDirectory + 'video.mp4');
console.log("download complete. File "+localUri);
}
return (
<View style={{flex:1, alignItems: "center", justifyContent: "center"}}>
<Button title="download" onPress={download}></Button>
</View>
);
}
Full Documentation

Related

Problem with iFrame in React rendering another app (flutter app)

I have a React app that is using an iFrame to render another app that was made in flutter (see the first image):
The flutter app is hosted in a certain domain (so it's like a micro frontend). The app in React is the dashboard and is hosted somewhere else (different than the flutter app)
My problem is that when testing the flutter app directly in the hosted URL, it works as expected. When you click on the name of one person, a sidebar opens with some information and a button "Gestion oferta".
When you click on the button, it should take you to this other view:
So this works as expected if I test the flutter app directly in the URL where it is hosted, but when I click on that button inside the react dashboard, it does not behave as expected, it just shows another instance of the same react app (dashboard) inside the iFrame, like this:
Here is my code for this component in the react app that renders the iFrame, in which I call the URL for the flutter app:
import { Fragment } from "react";
import { css } from '#emotion/react'
import Head from "next/head";
import DashboardLayout from "../../../layouts/DashboardLayout";
import { getTenantByCompanySiap } from "../../../helpers/tentant";
import { UAT, PROD, getEnv } from "../../../helpers/env";
export { getSSProps as getServerSideProps } from '../../../lib/Page'
export default function NuevaSolicitudPage(props) {
const tenant = getTenantByCompanySiap(props.infoRh?.codeCompanySIAP)
const branch = props.infoRh?.codeBranch
const user = props.employeeData?.email
const getCampanas = () => {
const env = getEnv();
const url = {
[UAT]: `https://url-for-testing`,
[PROD]: `https://other-url-for-production`
};
return url[env] || url[UAT];
};
const url = getCampanas()
return (
<Fragment>
<Head>
<title>Gestión de cartera | Campañas</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<DashboardLayout
{...props}
title="Campanas"
>
<iframe
src={url}
css={css`
width: 100%;
height: 100%;
`}
frameBorder="0"
/>
</DashboardLayout>
</Fragment>
);
}
I do not have access to the flutter app code, I only consume it and show it in the iFrame, but I heard from someone that I need to configure some files in order to display flutter apps in an iFrame in react, but he is also not sure. I have searched for something like this but could not find anything relevant to this problem because the app is showing, it just does not behave as expected.
Can somebody give me an advice on how to solve this issue? Thanks in advance.
This issue had to do with the cookies, somehow the cookie to store the user session got lost/erased, so whenever you have something similar and you use cookies for user sessions, check if they are stored and used properly.

when I connect the api to my react code it gets error 401(unauthorized access)

I want to make a recipes website and got the API key from spoonacular. when I run the website it says I have unauthorized access. I tried canceling and restarting the npm, flushing my DNS, clearing my cache, restarting my computer, and generating a new key, i even deleted the application and rewrote the code but nothing seems to work.
I'm using vs code.
here's the code:
import React from 'react'
import {useEffect} from "react";
function Pop() {
useEffect(() => {
getPop();
},[]);
const getPop = async() =>{
const api = await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_KEY}&number=9`);
const data = await api.json();
console.log(data);
}
return (
<div>Pop</div>
)
}

How to use Flask to route with a React app?

I'm a React developer who's new to Flask. I'd like to route in backend with Flask and build frontend with React. My first scaffold looks like this:
Folder structure:
react-flask-app
-api
-app.py
-public
-index.html
-src
-pages
-Home.js
-Page1.js
-components
-Navbar.js
-App.js
App.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('../public/index.html')
Navbar.js:
const Navbar = () => {
return (
<>
<a href='/'>Home</a>
<a href='/page1'>Page 1</a>
</>
)
};
Home.js:
import Navbar from '../components/Navbar';
const Home = () => {
return (
<>
<Navbar />
<div>Homepage</div>
</>
)
}
Page1.js
import Navbar from '../components/Navbar';
const Page1 = () => {
return (
<>
<Navbar />
<div>Page 1</div>
</>
)
}
When I run the React app, I can switch between http://localhost:3000/ and http://localhost:3000/page1 by clicking the Navbar buttons, but it does not display Page1, since I've not set routing yet.
My question is, I know Flask can be used for routing, how can I use Flask to route and link to each page in this case?
To tell react to proxy any requests to Flask, add a proxy field to your package.json, e.g
"proxy": "http://localhost:5000",
Then use ajax, fetch from within your components to access your API.
More Information can be found in Proxying in development

How to generate the downloaded pdf from react-pdf without clicking the download link?

I'm currently creating a pdf using react-pdf. Instead of providing a download link with the PDFDownloadLink component, I want to run the program and have it automatically create and download the pdf. I'm not very familiar with react, is there a way I can have it click the link once it is rendered? Is there a better way? Ideally, I'd like to create a command like "yarn generate" and it outputs the pdf that gets rendered. Any help is appreciated!
import React from 'react';
import { BlobProvider, PDFDownloadLink, PDFViewer} from '#react-pdf/renderer'
import './App.css';
import { MyPDF} from "./components/MyPDF";
function App() {
return (
<div className="App">
<div>
<PDFDownloadLink document={<MyPDF/>} fileName="mypdf.pdf">
{({ blob, url, loading, error }) => {
console.log(blob);
return (loading ? 'Loading document...' : 'Download the pdf')}
}
</PDFDownloadLink>
</div>
</div>
);
}
export default App;

Next.js hangs while setting initial props on server-side

I am trying to set up SSR with Nextjs.
I have following code, where I am fetching json data and binding them as initial props.
When I am in development mode all works correctly, when I deploy to the server fetching works only on client-side (when I navigate from other view).
If I try to load directly the page with fetching, server hangs, no error.
I should add that all is running inside Docker container, but I guess it should not matter at this case.
Here is code
import React from 'react'
import { get } from 'axios'
import Layout from '../components/Layout/Layout'
import WorkSingle from '../components/Work/WorkSingle/WorkSingle'
import DocumentTitle from '../hoc/DocumentTitle/DocumentTitle'
const Work = (props) => {
let works = 'Loading...'
if (props.workData.length > 0)
works = props.workData.map(work => (
<WorkSingle
img={work.image}
url={work.url}
title={work.title}
key={work.title}
/>
))
return (
<Layout>
<DocumentTitle title='Some page title' />
<section id="work">
<h1 className="font_title">WORK</h1>
<div className="row">
{works}
</div>
</section>
</Layout>
)
}
Work.getInitialProps = async () => {
const response = await get('VALID_URL')
if (response && response.data)
return { workData: response.data.work }
return {}
}
export default Work
I have solved it, problem was that i wanted to fetch static data from the same server which is serving app, for some reason when server tried to fetch from itself it stuck, I put the resource I am fetching to another server for now and it solved problem.
I was mocking the data via static .json file, I guess when I create actual API endpoint it will work from the same server too.

Categories