質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

8081閲覧

CSRF検証に失敗したため、リクエストは中断されました。 のエラー

退会済みユーザー

退会済みユーザー

総合スコア0

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2017/08/02 04:46

Swiftのアプリから画像を選択し、PythonのDjangoで構築したサーバーに選択した画像をアップロードするシステムを作っています。Swiftの画像をアップロードするPhotoControllerに

import Foundation import MobileCoreServices import UIKit class PhotoController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! @IBOutlet weak var myImageView: UIImageView! private var imagePicker:UIImagePickerController! var textField: UITextField! @IBAction func uploadButtonTapped(_ sender: Any) { myImageUploadRequest() } override func viewDidLoad() { super.viewDidLoad() label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.text = "Tap the PhotoSelect or Camera to upload a picture" myActivityIndicator.hidesWhenStopped = true textField = UITextField() } @IBAction func PhotoSelect(_ sender: Any) { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(myPickerController, animated: true, completion: nil) } @IBAction func Camera(_ sender: Any) { let sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.camera // カメラが利用可能かチェック if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){ // インスタンスの作成 let cameraPicker = UIImagePickerController() cameraPicker.sourceType = sourceType cameraPicker.delegate = self self.present(cameraPicker, animated: true, completion: nil) } else{ label.text = "error" } } // 撮影が完了時した時に呼ばれる func imagePickerController(_ imagePicker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { myImageView.contentMode = .scaleAspectFit myImageView.image = pickedImage } //閉じる処理 imagePicker.dismiss(animated: true, completion: nil) label.text = "Tap the Send to save a picture" } // 撮影がキャンセルされた時に呼ばれる func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) label.text = "Canceled" } // override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //画像のアップロード処理 func myImageUploadRequest(){ //myUrlにはphpファイルのアドレスを入れる let myUrl = NSURL(string:"http://localhost:8000/admin/accounts/post/42/change/"); let request = NSMutableURLRequest(url:myUrl! as URL) request.httpMethod = "POST" let boundary = generateBoundaryString() request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let imageData = UIImageJPEGRepresentation(self.myImageView.image!, 1) if(imageData==nil) { return; } var name = "" if let text = textField.text { name = text } let postString = "name=\(name)" // let postString = "name=\(textField.text!)" request.httpBody = postString.data(using: .utf8) //myActivityIndicator.startAnimating(); let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in if error != nil { print("error=\(error)") return } // レスポンスを出力 print("******* response = \(response)") let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print("****** response data = \(responseString!)") DispatchQueue.main.async(execute: { //アップロード完了 }); } task.resume() } func generateBoundaryString() -> String { return "Boundary-\(NSUUID().uuidString)" } }

と書きました。
そして、エミュレーターを立ち上げ画像を選択し送信ボタンを押すと

bjc[13221]: Class PLBuildVersion is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x11b60c998) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x11a4f7880). One of the two will be used. Which one is undefined. 2017-08-02 13:38:58.029238 XXX[13221:1089438] [Generic] Creating an image format with an unknown type is an error here Optional(<UIImage: 0x60000028ae10> size {3000, 2002} orientation 0 scale 1.000000) ******* response = Optional(<NSHTTPURLResponse: 0x60000042bac0> { URL: http://localhost:8000/admin/accounts/post/42/change/ } { status code: 403, headers { "Content-Type" = "text/html"; Date = "Wed, 02 Aug 2017 04:38:59 GMT"; Server = "WSGIServer/0.1 Python/2.7.11"; "X-Frame-Options" = SAMEORIGIN; } }) ****** response data = <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>アクセス禁止 <span>(403)</span></h1> <p>CSRF検証に失敗したため、リクエストは中断されました。</p> <p>このメッセージが表示されている理由は、このサイトはフォーム送信時にCSRFクッキーを必須としているためです。このクッキーはセキュリティ上の理由(使用中のブラウザが第三者によってハイジャックされていないことを確認するため)で必要です。</p> <p>もしブラウザのクッキーを無効に設定しているならば、same-originリクエストのために少なくともこのサイトでは再度有効にしてください。</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF cookie not set. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/1.10/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to the template's <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li> <li>In the template, there is a <code>{% csrf_token %}</code> template tag inside each POST form that targets an internal URL.</li> <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li> <li>The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.</li> </ul> <p>You're seeing the help section of this page because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and only the initial error message will be displayed. </p> <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> </div> </body> </html>

とエラーが出ました。これはSwift側を直せば良いのでしょうか?それともPython側を直せば良いのでしょうか?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

あまり詳しくないのですが、DjangoのCSRFトークンを無効化すればいいのでは。
クロスサイトリクエストフォージェリ (CSRF) 対策 — Django 1.4 documentation

投稿2017/08/02 05:08

Lhankor_Mhy

総合スコア36104

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問