def saveAndPushToR2(self, filename):
# Use self.engine
currentDateFileFormat = datetime.now().strftime("%d_%m_%Y")
# filename = f"{category}_{currentDateFileFormat}.json"
s3 = boto3.resource('s3',
endpoint_url=f'https://{environ.get("ACCOUNT_ID")}.r2.cloudflarestorage.com',
aws_access_key_id=environ.get("ACCESS_KEY_ID"),
aws_secret_access_key=environ.get(
"SECRET_ACCESS_KEY")
)
with open(filename, "r"):
# s3.Bucket(environ["BUCKET_NAME"]).put_object(
# Key=filename, Body=f, ContentType="application/json"
# )
s3.Bucket(environ["BUCKET_NAME"]).upload_file(
filename, filename, ExtraArgs={'ContentType': "application/json"}
)
logging.info(
f"{filename} uploaded successfully to Cloudflare R2."). raise S3UploadFailedError(
boto3.exceptions.S3UploadFailedError: Failed to upload prepositions_03_11_2023.json to production/prepositions_03_11_2023.json: An error occurred (Unauthorized) when calling the PutObject operation: Unauthorized
2023-11-03 18:17:55 [scrapy.extensions.feedexport] INFO: Stored json feed (49 items) in: output.json this is error

def saveAndPushToR2(self, filename):
# Use self.engine
currentDateFileFormat = datetime.now().strftime("%d_%m_%Y")
# filename = f"{category}_{currentDateFileFormat}.json"
s3 = boto3.resource('s3',
endpoint_url=f'https://{environ.get("ACCOUNT_ID")}.r2.cloudflarestorage.com',
aws_access_key_id=environ.get("ACCESS_KEY_ID"),
aws_secret_access_key=environ.get(
"SECRET_ACCESS_KEY")
)
with open(filename, "r"):
# s3.Bucket(environ["BUCKET_NAME"]).put_object(
# Key=filename, Body=f, ContentType="application/json"
# )
s3.Bucket(environ["BUCKET_NAME"]).upload_file(
filename, filename, ExtraArgs={'ContentType': "application/json"}
)
logging.info(
f"{filename} uploaded successfully to Cloudflare R2."). raise S3UploadFailedError(
boto3.exceptions.S3UploadFailedError: Failed to upload prepositions_03_11_2023.json to production/prepositions_03_11_2023.json: An error occurred (Unauthorized) when calling the PutObject operation: Unauthorized
2023-11-03 18:17:55 [scrapy.extensions.feedexport] INFO: Stored json feed (49 items) in: output.json<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
</Error>getSignedUrl(s3, new PutObjectCommand({
Bucket: bucket,
Key: `${fileName}`
}), { expiresIn: 600 })// getS3Client.ts
import { S3Client } from "@aws-sdk/client-s3";
import { getDotenv } from "./getEnv";
let s3Client: S3Client | undefined = undefined;
const env = getDotenv();
export const getS3Client: () => S3Client = () => {
console.log(env);
if (s3Client === undefined) {
s3Client = new S3Client({
region: "auto",
endpoint: `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: env.R2_ACCESS_KEY_ID,
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
},
});
return s3Client;
}
return s3Client;
};const s3Client = getS3Client();
const env = getDotenv();
const resizeImage = async (str: string) => {
// TODO:
await sharp(str).webp({ quality: 75 }).toBuffer();
};
export const uploadDirectlyOne = async (path: string, body: string) => {
// TODO: test it
console.log("uploading:", path);
const buf = Buffer.from(body, "utf8");
const command = new PutObjectCommand({
Bucket: env.S3_BUCKET,
Key: path,
Body: buf,
});
try {
const response = await s3Client.send(command);
console.log("uploaded:", path);
} catch (err) {
console.error(err);
throw err;
}
};// Size is sent over by the client. It is checked against the maximum allowed file size on the server
const chunkCount = Math.ceil(size / FILE_CHUNK_SIZE_BYTES);
const fileKey = "my/r2/file_key";
const uploadSessionId = "R2_MULTIPART_SESSION_ID";
const presignedUrls = [];
for(let x = 1; x <= chunkCount; x++) {
presignedUrls.push(await r2.getPresignedChunkUrl(fileKey, uploadSessionId, x, (60 * 60 * 24), x < chunkCount ? FILE_CHUNK_SIZE_BYTES : (size % FILE_CHUNK_SIZE_BYTES)));
}async getPresignedChunkUrl(key: string, uploadSessionId: string, partNumber: number, expiresInSec: number, contentLength: number) {
try {
const command = new UploadPartCommand({
Bucket: this.bucket,
Key: key,
UploadId: uploadSessionId,
PartNumber: partNumber,
ContentLength: contentLength
});
return await getSignedUrl(this.client, command, {expiresIn: expiresInSec});
}
catch (e: any) {
console.error(e?.message);
}
return null;
}